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):
14 def __complex__(self): return complex(self.eval())
15 def __int__(self): return int(self.eval())
16 def __long__(self): return long(self.eval())
17 def __float__(self): return float(self.eval())
18 def __pos__(self): return self # positive
19 def __neg__(self): return Unop('-', self)
20 def __add__(self, other): return Binop('+', self, other)
21 def __radd__(self, other): return Binop('+', other, self)
22 def __sub__(self, other): return Binop('-', self, other)
23 def __rsub__(self, other): return Binop('-', other, self)
24 def __mul__(self, other): return Binop('*', self, other)
25 def __rmul__(self, other): return Binop('*', other, self)
26 def __div__(self, other): return Binop('/', self, other)
27 def __truediv__(self, other): return Binop('/', self, other)
28 def __rdiv__(self, other): return Binop('/', other, self)
29 def __pow__(self, other): return Binop('**', self, other)
30 def __rpow__(self, other): return Binop('**', other, self)
31 def __getitem__(self,i):return Binop('[]',self,i)
34 opmap = { '+': 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,
39 '[]': lambda a, b: a[b] ,
41 def __init__(self, op, value1, value2):
43 self.values = mkf(value1), mkf(value2)
46 return "(%s[%s])" % (self.values[0], self.values[1])
48 return "(%s %s %s)" % (self.values[0], self.op, self.values[1])
51 return "(%s[%s])" % (self.values[0], self.values[1])
53 return "(%s %s %s)" % (self.values[0], self.op, self.values[1])
55 result= self.opmap[self.op](self.values[0].eval(),
56 self.values[1].eval())
57 while isinstance(result,Formula):
62 opmap = { '-': lambda x: -x,
63 'sin': lambda x: math.sin(x),
64 'cos': lambda x: math.cos(x) }
65 def __init__(self, op, arg):
69 return "%s(%s)" % (self._op, self._arg)
71 return self.opmap[self._op](self._arg.eval())
73 class Constant(Formula):
74 def __init__(self, value): self._value = value
75 def eval(self): return self._value
76 def __str__(self): return str(self._value)
78 class Variable(Formula):
79 def __init__(self,name,value):
82 def eval(self): return self._value
83 def __repr__(self): return "Variable('%s',%s)" % (self._name, self._value)
84 def __str__(self): return self._name
86 def cos(f): return Unop('cos', f)
87 def sin(f): return Unop('sin', f)