1 from __future__ import division
5 if type(value) in (type(1), type(1L), type(1.5), type(1j),type("hh")):
7 elif isinstance(value, Formula):
10 raise TypeError, ("Can't make formula from", value)
12 class Formula(object):
13 def __complex__(self): return complex(self.eval())
14 def __int__(self): return int(self.eval())
15 def __long__(self): return long(self.eval())
16 def __float__(self): return float(self.eval())
17 def __pos__(self): return self # positive
18 def __neg__(self): return Unop('-', self)
19 def __add__(self, other): return Binop('+', self, other)
20 def __radd__(self, other): return Binop('+', other, self)
21 def __sub__(self, other): return Binop('-', self, other)
22 def __rsub__(self, other): return Binop('-', other, self)
23 def __mul__(self, other): return Binop('*', self, other)
24 def __rmul__(self, other): return Binop('*', other, self)
25 def __div__(self, other): return Binop('/', self, other)
26 def __truediv__(self, other): return Binop('/', self, other)
27 def __rdiv__(self, other): return Binop('/', other, self)
28 def __pow__(self, other): return Binop('**', self, other)
29 def __rpow__(self, other): return Binop('**', other, self)
30 def __getitem__(self,i):return Binop('[]',self,i)
33 opmap = { '+': lambda a, b: a + b,
34 '*': lambda a, b: a * b,
35 '-': lambda a, b: a - b,
36 '/': lambda a, b: a / b,
37 '**': lambda a, b: a ** b,
38 '[]': lambda a, b: a[b] ,
40 def __init__(self, op, value1, value2):
42 self.values = mkf(value1), mkf(value2)
45 return "(%s[%s])" % (self.values[0], self.values[1])
47 return "(%s %s %s)" % (self.values[0], self.op, self.values[1])
50 return "(%s[%s])" % (self.values[0], self.values[1])
52 return "(%s %s %s)" % (self.values[0], self.op, self.values[1])
54 result= self.opmap[self.op](self.values[0].eval(),
55 self.values[1].eval())
56 while isinstance(result,Formula):
61 opmap = { '-': lambda x: -x,
62 'sin': lambda x: math.sin(x),
63 'cos': lambda x: math.cos(x) }
64 def __init__(self, op, arg):
68 return "%s(%s)" % (self._op, self._arg)
70 return self.opmap[self._op](self._arg.eval())
72 class Constant(Formula):
73 def __init__(self, value): self._value = value
74 def eval(self): return self._value
75 def __str__(self): return str(self._value)
77 def cos(f): return Unop('cos', f)
78 def sin(f): return Unop('sin', f)