Sahil Soni
Sahil Soni

Reputation: 67

How to substitute values in mathematics equations in python?

I am getting data in form of dictionary from data base as:

in_dict = {"x":2,"y":"x+2","z":"y+2"}

and I am getting my maths equation in form of string as :

eqn = "(x+2)*y/z"

What is the easiest method to substitute values in equation and to give final solution?

Note: One should be aware that values in dictionary come randomly.

Upvotes: 1

Views: 5652

Answers (4)

Patrick O'Connor
Patrick O'Connor

Reputation: 334

Building off of the previous sympy answer, here is an approach which is dynamic with respect to the size and content of the in_dict variables. The biggest step is to map the sympy symbols (python vars of x, y, z) to their symbolic representations that get passed through your in_dict

import sympy

def eval_eqn(eqn,in_dict):
    subs = {sympy.symbols(key):item for key,item in in_dict.items()}
    ans = sympy.simplify(eqn).evalf(subs = subs)

    return ans

The original inputs:

in_dict = {"x":2,"y":"x+2","z":"y+2"}
eqn = "(x+2)*y/z"
print(eval_eqn(eqn,in_dict))

2.66666666666667

A different set of inputs:

in_dict = {"a":2, "b": 4, "c":"a+2*b","d":"4*b + c"}
eqn = "c**2 + d**2"
print(eval_eqn(eqn,in_dict))

776.000000000000

Upvotes: 2

Sohaib Farooqi
Sohaib Farooqi

Reputation: 5666

You can use Sympy to solve these equations. Install it if you don't already have it using pip install sympy

import sympy

in_dict = {"x":2,"y":"x+2","z":"y+2"}
x, y, z = sympy.symbols('x y z')
sympy.sympify("(x+2)*y/z").evalf(subs={x:in_dict['x'], y:in_dict['y'], z:in_dict['z']})

This will give you output as: 2.66666666666667

Upvotes: 2

Ganesh Kathiresan
Ganesh Kathiresan

Reputation: 2088

Assuming you have only three variables,

x = d["x"]
y = eval(d["y"]) # as it is a string
z = eval(d["z"]) # as it is a string

You can use eval:

x = eval("(x+2)*y/z")

[EDIT 2] You can use itemgetter for unpacking:

>>> from operator import itemgetter
>>> stuff = {'a': '1', 'b': 'a+1', 'c': '3', 'd': '4'}
>>> a, b, c = list(map(eval, itemgetter('a', 'b', 'c')(stuff))) # for automatic evaluation, but all must be string
>>> a, b, c
(1, 2, 3)

Upvotes: 2

Sharad
Sharad

Reputation: 10602

Sample code:

from __future__ import division
foo = {"x":2,"y":"x+2","z":"y+2"}
x = "(x+2)*y/z"
x = ("(x+2)*y/z"
     .replace('z', '({})'.format(foo['z']))
     .replace('y', '({})'.format(foo['y']))
     .replace('x', '({})'.format(foo['x'])))
print('x = {}'.format(x))
print('x = {}'.format(eval(x)))

Sample output:

x = ((2)+2)*((2)+2)/(((2)+2)+2)
x = 2.66666666667

Upvotes: 1

Related Questions