forked from yuemingl/SymJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReciprocal.java
More file actions
90 lines (77 loc) · 2.47 KB
/
Reciprocal.java
File metadata and controls
90 lines (77 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package symjava.symbolic;
import java.util.Map;
import symjava.symbolic.arity.UnaryOp;
import symjava.symbolic.utils.BytecodeUtils;
import symjava.symbolic.utils.Utils;
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.InstructionConstants;
import com.sun.org.apache.bcel.internal.generic.InstructionFactory;
import com.sun.org.apache.bcel.internal.generic.InstructionHandle;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.bcel.internal.generic.MethodGen;
public class Reciprocal extends UnaryOp {
public Reciprocal(Expr base) {
super(base);
updateLabel();
}
@Override
public Expr diff(Expr expr) {
return new Negate(Pow.simplifiedIns(arg,Expr.valueOf(-2))).multiply(arg.diff(expr));
}
@Override
public Expr simplify() {
if(this.isSimplified)
return this;
if(arg instanceof Pow) {
Pow p = (Pow)arg.simplify();
p.isSimplified = true;
Expr rlt = Pow.simplifiedIns(p.arg1, p.arg2.negate());
rlt.isSimplified = true;
return rlt;
}
this.isSimplified = true;
return this;
}
public static Expr simplifiedIns(Expr expr) {
if(expr instanceof SymReal<?>) {
Number n = (Number)((SymReal<?>)expr).getValue();
return new SymDouble(1.0/n.doubleValue());
}
return new Reciprocal(expr);
}
@Override
public boolean symEquals(Expr other) {
if(other instanceof Reciprocal) {
Reciprocal o = (Reciprocal)other;
return arg.symEquals(o.arg);
} else if(other instanceof Divide) {
Divide o = (Divide)other;
return o.arg1.symEquals(Symbol.C1) && arg.symEquals(o.arg2);
}
return false;
}
@Override
public Expr subs(Expr from, Expr to) {
if(Utils.symCompare(this, from))
return to;
if(arg.subs(from,to) == arg)
return this;
return Reciprocal.simplifiedIns(arg.subs(from, to));
}
@Override
public InstructionHandle bytecodeGen(String clsName, MethodGen mg,
ConstantPoolGen cp, InstructionFactory factory,
InstructionList il, Map<String, Integer> argsMap, int argsStartPos,
Map<Expr, Integer> funcRefsMap) {
InstructionHandle startPos = il.append(InstructionConstants.DCONST_1);
arg.bytecodeGen(clsName, mg, cp, factory, il, argsMap, argsStartPos, funcRefsMap);
BytecodeUtils.typeCast(il, arg.getType(), TYPE.DOUBLE);
il.append(InstructionConstants.DDIV);
return startPos;
}
@Override
public void updateLabel() {
label = "1/" + SymPrinting.addParenthsesIfNeeded(arg, this);
sortKey = arg.getSortKey();
}
}