Mathematical equation manipulation in Python

Leafy picture Leafy · Jun 18, 2009 · Viewed 15.1k times · Source

I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.

For example:


a = (b+c*d)/e

Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:

d = (a*e - b)/c

As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.

Is that the only way to go or is there any simpler suggestion? Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions.

But that is just my opinion, so please point out if I am wrong. Also, I will be using SymPy for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem.

Answer

Paul picture Paul · Jun 18, 2009

Using SymPy, your example would go something like this:

>>> import sympy
>>> a,b,c,d,e = sympy.symbols('abcde')
>>> r = (b+c*d)/e
>>> l = a
>>> r = sympy.solve(l-r,d)
>>> l = d
>>> r
[(-b + a*e)/c]
>>> 

It seems to work for trigonometric functions too:

>>> l = a
>>> r = b*sympy.sin(c)
>>> sympy.solve(l-r,c)
[asin(a/b)]
>>> 

And since you are working with a GUI, you'll (probably) want to convert back and forth from strings to expressions:

>>> r = '(b+c*d)/e'
>>> sympy.sympify(r)
(b + c*d)/e
>>> sympy.sstr(_)
'(b + c*d)/e'
>>> 

or you may prefer to display them as rendered LaTeX or MathML.