forked from yuemingl/SymJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNegate.java
More file actions
104 lines (92 loc) · 2.27 KB
/
Negate.java
File metadata and controls
104 lines (92 loc) · 2.27 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package symjava.symbolic;
import java.util.ArrayList;
import java.util.List;
import symjava.symbolic.arity.UnaryOp;
import symjava.symbolic.utils.Utils;
public class Negate extends UnaryOp {
public Negate(Expr expr) {
super(expr);
label = "-" + SymPrinting.addParenthsesIfNeeded(expr, this);
sortKey = arg.getSortKey();
}
@Override
public Expr diff(Expr expr) {
Expr d = arg.diff(expr);
if(d instanceof SymReal<?>) {
if(d instanceof SymInteger) {
return new SymInteger(-((SymInteger)d).getValue());
}
if(d instanceof SymLong) {
return new SymLong(-((SymLong)d).getValue());
}
SymReal<?> dd = (SymReal<?>)d;
double dv = dd.getValue().doubleValue();
if(dv == 0.0)
return new SymDouble(0.0);
return new SymDouble(-dv);
}
return Negate.simplifiedIns(arg.diff(expr));
}
public static Expr simplifiedIns(Expr expr) {
if(expr instanceof SymReal<?>) {
Number n = ((SymReal<?>)expr).getValue();
return new SymDouble(-n.doubleValue());
} else if(expr instanceof Negate) {
Negate n = (Negate)expr;
return n.arg;
}
return new Negate(expr);
}
@Override
public Expr subs(Expr from, Expr to) {
if(arg.subs(from,to) == arg)
return this;
return Negate.simplifiedIns(arg.subs(from, to));
}
@Override
public Expr simplify() {
if(this.isSimplified)
return this;
Expr nb = arg.simplify();
nb.isSimplified = true;
Expr rlt = new Negate(nb);
rlt.isSimplified = true;
return rlt;
}
@Override
public boolean symEquals(Expr other) {
if(other instanceof Negate && arg.symEquals(((Negate)other).arg))
return true;
return false;
}
@Override
public void flattenAdd(List<Expr> outList) {
List<Expr> list1 = new ArrayList<Expr>();
arg.flattenAdd(list1);
if(list1.size() == 1) {
outList.add(this);
} else {
for(Expr e : list1) {
outList.add( new Negate(e) );
}
}
}
@Override
public void flattenMultiply(List<Expr> outList) {
List<Expr> tmp = new ArrayList<Expr>();
arg.flattenMultiply(tmp);
if(tmp.size() == 1)
outList.add(this);
else {
int sign = Utils.getMultiplyGlobalSign(tmp);
Utils.removeNegate(tmp);
if(sign == 1)
outList.add(new Negate(tmp.get(0)));
else
outList.add(tmp.get(0));
for(int i=1; i<tmp.size(); i++) {
outList.add(tmp.get(i));
}
}
}
}