Mathematical expression evaluator in python

VM Vera Mazhuga Vera Mazhuga

Vera Mazhuga

Software Developer
2 min read.

In this post we will take look at how to parse and execute mathematical expressions in python.


Sometimes we face tasks when we need to ask our users not only to enter some values, but to write down the whole formula in order to calculate the values we need automatically. In this case we have to ask them to write a mathematical expression and then enter the values of its variables.


For example, we need to obtain a position of some object that is moving in the space, but we know nothing about the law of motion that makes this object move this way. So firstly we have to ask a user to enter an equation of motion. If the object moves with uniform acceleration, the user will provide us the following formula:



So we have pase an expression that looks like this:

x + v * t + a * t^2 / 2


where
x and v are the object's initial position and velocity, t is time and a is acceleration of the object.


To parse these types of expressions we a going to use a python version of the
js-expression-eval plugin: py-expression-eval. Firstly we create a Parser object and then use the method parse to obtain the corresponding Expression instance:

>>>> from parser import Parser
>>> parser = Parser()
>>> parser.parse('x + v * t + a * t^2 / 2')
>>> parser.Expression instance at 0x10557ddd0


Now we can extract a list of variables from our expression using the method variables:

>>> expr = parser.parse('x + v * t + a * t^2 / 2')
>>> expr.variables()
['x', 'v', 't', 'a']


If the expression looks too complicated or we already have some values of the variables, we can simplify the formula converting it to a shorter and simpler expression:

>>> expr.simplify({}).toString()
'((x+(v*t))+(a*((t^2.0)/2.0)))'
>>> expr.simplify({'t': 2}).toString()
'((x+(v*2))+(a*2.0))'


Another example:

>>> parser = Parser()
>>> parser.parse('2 * 3  + x').simplify({'t': 2}).toString()
'(6.0+x)'


To evaluate our expression (assign values to variables) we'll use the method
evaluate, to which we'll pass a dictionary where the keys are the names of our variables:

>>> parser = Parser()
>>> parser.evaluate('3  + x', {'x': 2})
5.0

Written by Vera Mazhuga

VM Vera Mazhuga Vera Mazhuga

Vera specializes in writing and maintaining code for various applications. Her focus on problem-solving and efficient programming ensures reliable and effective software solutions.

Newsletter

Subscribe to our newsletter:

Read more

Primeros días en AxiaCore

Hace más o menos un mes, mientras aún trabajaba en mi antigua compañía, decidí asistir a una de las conferencias sobre Django...

· 1 min read.

Pointer events en CSS

Sin importar el orden de apilamiento o posición es posible controlar por medio de css con una simple propiedad el evento del...

· 1 min read.

Build Once. Own Forever.