我需要一个在python中使用渐近的计算下面的表达式?
exp = '(a+b)*40-(c-a)/0.5'在a=6,b=5,c=2这种情况下,如何在python中使用渐近来计算表达式?请帮帮我。
发布于 2011-08-10 14:32:17
文档在这里: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})发布于 2012-11-05 11:28:37
您可以使用the parse_expr() function in the module sympy.parsing.sympy_parser将字符串转换为渐近表达式。
>>> 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发布于 2013-02-12 07:10:18
我意识到上面已经回答了这个问题,但是在获取包含未知符号的字符串表达式并需要访问这些符号的情况下,下面是我使用的代码
# 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)https://stackoverflow.com/questions/7006626
复制相似问题