Portafolio Servicios Clientes Nosotros Blog Contacto

Mathematical expression evaluator in python

Foto del autor: Vera Mazhuga

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

Domingo es tu día para empezar

Hemos ayudado cientos de empresas a transformar su negocio. ¡Comencemos a transformar el tuyo!

Calle 100 # 14 - 63 OF 801
Bogotá - Colombia