Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical equation manipulation in Python

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.

like image 462
Leafy Avatar asked Jun 18 '09 03:06

Leafy


People also ask

Can Python rearrange equations?

If we have numerical values for z, a and b, we can use Python to calculate the value of y. However, if we don't have numerical values for z, a and b, Python can also be used to rearrange terms of the expression and solve for the variable y in terms of the other variables z, a and b.


1 Answers

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.

like image 170
Paul Avatar answered Oct 06 '22 18:10

Paul