-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate.py
61 lines (50 loc) · 1.31 KB
/
evaluate.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
import math
from typing import Dict
from cas.model import *
class UnboundVariableError(RuntimeError):
pass
# Node Evaluation
def evaluate(n: Node, bound_vars: Dict[str, Node] = None):
assert n.is_node, f'Parameter {n}: {type(n)} is not a node'
bound_vars = bound_vars or dict()
if type(n) == Num:
return n.val
elif type(n) == Var:
val = bound_vars.get(n.name)
if val is None:
raise UnboundVariableError(f"Error: Unbound variable '{n.name}'")
return evaluate(val, bound_vars)
elif type(n) == Function:
f = {
'sin': math.sin,
'cos': math.cos,
'tan': math.tan,
'sqrt': math.sqrt,
'log': math.log10,
'ln': math.log
}[n.f.value]
x = evaluate(n.x, bound_vars)
return f(x)
elif type(n) == UnaryOp:
x = evaluate(n.a, bound_vars)
if n.op == UnaryOp.Op.NEG:
return -1 * x
else:
assert False, f'Unhandled unary operation {n.op}'
elif type(n) == BinaryOp:
a = evaluate(n.a, bound_vars)
b = evaluate(n.b, bound_vars)
if n.op == BinaryOp.Op.ADD:
return a + b
elif n.op == BinaryOp.Op.SUB:
return a - b
elif n.op == BinaryOp.Op.MUL:
return a * b
elif n.op == BinaryOp.Op.DIV:
return a / b
elif n.op == BinaryOp.Op.EXP:
return a ** b
else:
assert False, f'Unhandled binary operation {n.op}'
else:
print(f'evaluate: unimplemented node type {type(n)}')