KickJava   Java API By Example, From Geeks To Geeks.

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


1 package JSci.maths.symbolic;
2  
3 import JSci.maths.*;
4 import JSci.maths.fields.*;
5 import JSci.maths.groups.*;
6
7 import java.util.*;
8
9 class Power extends Expression {
10
11     private final Expression base;
12     private final int exponent;
13
14     public Power(Expression b,int e) {
15     base=b;
16     exponent=e;
17     }
18
19     public Expression getBase() {return base;}
20     public int getExponent() {return exponent;}
21
22     public String JavaDoc toString() {
23     String JavaDoc r = "";
24     int ep;
25     if (base.getPriority()<getPriority()) r+="("+base+")";
26     else r+=""+base;
27     r+="^";
28     if (exponent>=0) ep=20; else ep=0;
29     if (ep<getPriority()) r+="("+exponent+")";
30     else r+=""+exponent;
31     return r;
32     }
33
34     public Expression differentiate(Variable x) {
35     return new Product(new Expression[] {
36         new Constant(new MathDouble(exponent)),
37         new Power(base,exponent-1),
38         base.differentiate(x)
39     });
40     }
41
42     public Expression evaluate() {
43     Expression b = base.evaluate();
44     if (b instanceof Constant) {
45         Field.Member p = (Field.Member)((Ring)((Constant)b).getValue().getSet()).one();
46         if (exponent>=0) {
47         Ring.Member c = (Ring.Member)((Constant)b).getValue();
48         for (int j=0;j<exponent;j++)
49             p=(Field.Member)p.multiply((Field.Member)c);
50         }
51         else {
52         Field.Member c = (Field.Member)((Constant)b).getValue();
53         c=c.inverse();
54         for (int j=0;j<-exponent;j++) p=(Field.Member)p.multiply(c);
55         }
56         return new Constant(p);
57     }
58     if (exponent==0) return new Constant(((Ring)base.getSet()).one());
59     if (exponent==1) return base;
60     return new Power(b,exponent);
61     }
62
63     protected int getPriority() {return 15;}
64
65     public Object JavaDoc getSet() { return base.getSet(); }
66
67 }
68
69
70
71
Popular Tags