KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JSci > maths > symbolic > Sum


1 package JSci.maths.symbolic;
2  
3 import JSci.maths.*;
4 import JSci.maths.groups.*;
5 import java.util.*;
6
7 class Sum extends Expression {
8     
9     private final List terms;
10     
11     public Sum(Expression [] a) {
12     terms = Arrays.asList(a);
13     }
14
15     public Sum(List a) {
16     terms = a;
17     }
18
19     public Sum(Expression a,Expression b) {
20     terms = new ArrayList();
21     terms.add(a);
22     terms.add(b);
23     }
24
25     public String JavaDoc toString() {
26     String JavaDoc r = "";
27     Expression f;
28     for (int j=0;j<terms.size();j++) {
29         if (j>0) r+="+";
30         f=(Expression)terms.get(j);
31         if (f.getPriority()<getPriority()) r+="("+f+")";
32         else r+=""+f;
33     }
34     return r;
35     }
36
37     public Expression differentiate(Variable x) {
38     List r = new ArrayList();
39     for (int j=0;j<terms.size();j++) {
40         r.add(((Expression)terms.get(j)).differentiate(x));
41     }
42     return new Sum(r);
43     }
44
45     public Expression evaluate() {
46     // svolge le somme contenute -> t
47
List t = new ArrayList();
48     for (int j=0;j<terms.size();j++) {
49         Expression f=((Expression)terms.get(j)).evaluate(); // recursive
50
if (f instanceof Sum)
51         for (int k=0;k<((Sum)f).terms.size();k++)
52             t.add(((Sum)f).terms.get(k));
53         else t.add(f);
54     }
55     // raccoglie le costanti -> s
56
AbelianGroup.Member c = null;
57     List s = new ArrayList();
58     for (int j=0;j<t.size();j++) {
59         Expression f=(Expression)t.get(j);
60         if (f instanceof Constant) {
61         if (c==null) c=(AbelianGroup.Member)((Constant)f).getValue();
62         else c = c.add((AbelianGroup.Member)((Constant)f).getValue());
63         }
64         else s.add(f);
65     }
66     if (c!=null && ! (((AbelianGroup)(c.getSet())).isZero(c)))
67         s.add(new Constant(c));
68
69     // eventualmente qui si possono raccogliere i termini uguali a meno di una costante
70
// AGGIUNGERE !!!
71

72     // ritorno
73

74     if (s.size()==0) return new Constant(((AbelianGroup)getSet()).zero());
75     if (s.size()==1) return (Expression)s.get(0);
76     return new Sum(s);
77     }
78
79     protected int getPriority() {return 0;}
80
81     public Object JavaDoc getSet() { return ((Member)terms.get(0)).getSet(); }
82
83 }
84
85
Popular Tags