symbolic computation, sort of

Tim Hochberg tim.hochberg at ieee.org
Wed Mar 12 16:40:49 EST 2003


Mathew Yeates wrote:
> Here a question that only a guru could answer.
> 
> I have a function which performs alot of numerical computations and I 
> want to symbolically see what equation is being computed. For instance, 
> I want to feed the function
> 
> def f(x):
>     t=2*x
>         b= t +1
>         return b
> 
> 
> to a tool and have it tell me that f(x) -> 2x+1
> 
> How could I go about doing such a thing? Its alot more complicated than 
> it looks because one would need to recursively examine any functions 
> that f calls.
> 
> Mathew
> 


One approach that may work, depending on the type of functions f calls, 
is to instrument x itself. Below is a partially implemented example.

Hope this is at least a little helpful,

-tim


import math

def sin(x):
     if isinstance(x, Eqn):
         return Eqn("sin(%s)" % str(x))
     return math.sin(x)

class Eqn:
     def __init__(self, rep):
         self._rep = rep
     def __str__(self):
         return self._rep
     def __repr__(self):
         return "Eqn(%s)" % self.__str__()
     def __mul__(self, other):
         return Eqn("(%s * %s)" % (str(self), str(other)))
     def __rmul__(self, other):
         return Eqn("(%s * %s)" % (str(other), str(self)))
     def __add__(self, other):
         return Eqn("(%s + %s)" % (str(self), str(other)))
     def __radd__(self, other):
         return Eqn("(%s + %s)" % (str(other), str(self)))

def f(x):
     t=2*x
     b= t +1
     return sin(b)


e = Eqn('x')
print f(e)

# This prints: sin(((2 * x) + 1))





More information about the Python-list mailing list