-
Notifications
You must be signed in to change notification settings - Fork 0
/
ruleset.py
68 lines (48 loc) · 1.59 KB
/
ruleset.py
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
from expr import Expr
from parse import parse
class RuleSet:
Rules = [
parse('_x-_x => 0'),
parse('_x/_x => 1'),
parse('_x+0 => _x'),
parse('_x*0 => 0'),
parse('_x*1 => _x'),
parse('_x*_x => _x^2'),
parse('_x^_n*_x^_m => _x^(_n+_m)'),
parse('_x^_n*_x => _x^(_n+1)'),
parse('0/_x => 0'),
parse('_x^_n/_x^_m => _x^(_n-_m)'),
parse('_x^_n/_x => _x^(_n-1)'),
parse('_x^1 => _x'),
parse('_x^0 => 1'),
parse('_x--_y => _x+-1*_y'),
parse('_x-(_x+_y) => -1*_y'), # TODO: find more elegant way to fix this
parse('(_a/_b)/(_c/_d) => (_a*_d)/(_b*_c)'),
# distributive property
parse('(_x*_n)+(_x*_m) => _x*(_n+_m)'),
parse('(_x*_n)+_x => _x*(_n+1)'),
parse('_x+_x => _x*2'),
### DERIVATIVE RULES ###
parse('d/d_x(_x) => 1'), # constant rule
parse('d/d_x(_n+_m) => d/d_x(_n)+d/d_x(_m)'), # sum rule
parse('d/d_x(_n-_m) => d/d_x(_n)-d/d_x(_m)'), # difference rule
parse('d/d_x(_m^_n) => _n*_m^(_n-1)*d/d_x(_m)'), # power rule
parse('d/d_x(_m*_n) => d/d_x(_m)*_n+_m*d/d_x(_n)'), # product rule
parse('d/d_x(_m/_n) => (_n*d/d_x(_m)-_m*d/d_x(_n))/_n^2'), # quotient rule
# chain rule
parse('d/d_x(sin(_y)) => cos(_y)*d/d_x(_y)'),
parse('d/d_x(cos(_y)) => -1*cos(_y)*d/d_x(_y)'),
]
def apply(expr: Expr) -> Expr:
for r in RuleSet.Rules:
expr = r.apply(expr)
return expr
def repeat_apply(expr: Expr) -> Expr:
prev = None
while prev is None or prev != expr:
prev = expr
expr = RuleSet.apply(expr).simplify()
return expr
if __name__ == '__main__':
r = RuleSet.Rules[-1]
print(r.apply(parse('(x*3)+(x*2)')))