[英]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. 注意:请注意,字典中的值是随机产生的。
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: 您可以使用eval:
x = eval("(x+2)*y/z")
[EDIT 2] You can use itemgetter for unpacking: [编辑2]您可以使用itemgetter进行拆箱:
>>> 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)
You can use Sympy to solve these equations. 您可以使用Sympy求解这些方程式。 Install it if you don't already have it using pip install sympy
如果尚未安装,请使用pip install sympy
进行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
这将为您提供输出: 2.66666666666667
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
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. 基于先前的sympy
答案,这是一种相对于in_dict
变量的大小和内容是动态的方法。 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
最大的步骤是将sympy符号( x, y, z
python变量)映射到通过in_dict
传递的符号表示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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.