我需要使用Python中的Sympy计算下面的表达式?
exp = '(a+b)*40-(c-a)/0.5'
在 a=6
,b=5
,c=2
的情况下,如何使用 Python 中的 Sympy 计算表达式?请帮帮我。
我需要使用Python中的Sympy计算下面的表达式?
exp = '(a+b)*40-(c-a)/0.5'
在 a=6
,b=5
,c=2
的情况下,如何使用 Python 中的 Sympy 计算表达式?请帮帮我。
这里是文档: http://docs.sympy.org/。你真的应该阅读它!
要“计算”您的表达式,请编写类似于以下内容的代码:
from sympy import Symbol
a = Symbol("a")
b = Symbol("b")
c = Symbol("c")
exp = (a+b)*40-(c-a)/0.5
就是这样。如果你对“计算”有其他含义,你也可以解决 exp = 0:
sympy.solve(exp)
> {a: [0.0476190476190476*c - 0.952380952380952*b],
> b: [0.05*c - 1.05*a],
> c: [20.0*b + 21.0*a]}
对于其他所有内容,您应该真正阅读文档。也许可以从这里开始:http://docs.sympy.org/0.7.1/tutorial.html#tutorial
更新:由于您在问题中添加了a、b、c的值,因此您可以将其添加到解决方案中:
exp.evalf(subs={a:6, b:5, c:2})
sympy.parsing.sympy_parser
中的parse_expr()
函数将字符串转换为sympy表达式。>>> from sympy.abc import a, b, c
>>> from sympy.parsing.sympy_parser import parse_expr
>>> sympy_exp = parse_expr('(a+b)*40-(c-a)/0.5')
>>> sympy_exp.evalf(subs={a:6, b:5, c:2})
448.000000000000
我知道这个问题已经在上面得到了回答,但是如果你需要访问那些未知符号的字符串表达式,以下是我使用的代码:
# sympy.S is a shortcut to sympify
from sympy import S, Symbol
# load the string as an expression
expression = S('avar**2 + 3 * (anothervar / athirdvar)')
# get the symbols from the expression and convert to a list
# all_symbols = ['avar', 'anothervar', 'athirdvar']
all_symbols = [str(x) for x in expression.atoms(Symbol)]
# do something with the symbols to get them into a dictionary of values
# then we can find the result. e.g.
# symbol_vals = {'avar': 1, 'anothervar': 2, 'athirdvar': 99}
result = expression.subs(symbols_vals)
我知道eval
是有害的,但是如果你的程序中已经定义了a、b和c,并且可以确保对于执行eval操作是安全的话,那么你就不需要使用sympy库了。
>>> a=5
>>> b=5
>>> c=2
>>> exp = '(a+b)*40-(c-a)/0.5'
>>> eval(exp)
406.0
>>> a, b, c = sympy.symbols('a b c')
>>> exp = (a + b) * 40 - (c - a) / 0.5
>>> exp.evalf(6, subs={a:6, b:5, c:2})
448.000
sympify()
函数的功能。如果您想要进行更多自定义操作,您也可以研究一下 Python 的tokenize
库(我只是觉得这很有趣)。 - eacousineau