【问题标题】:How to calculate expression using sympy in python如何在python中使用sympy计算表达式
【发布时间】:2011-08-10 06:18:26
【问题描述】:

我需要在 python 中使用 sympy 计算下面的表达式吗?

exp = '(a+b)*40-(c-a)/0.5'

a=6,b=5,c=2这种情况下如何在python中使用sympy计算表达式?请帮帮我。

【问题讨论】:

    标签: python expression sympy


    【解决方案1】:

    文档在这里: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 对象/将字符串表达式转换为 sympy 对象/。如何转换?
    • 我找到了解决方案。首先是“from sympy import S, Symbol”,然后是“exp = S('a+5')”。最后是“exp.evalf(subs={'a':7})”。谢谢你们。
    • 这是一个非常棒的解决方案 - 看起来它本质上是 sympify() 的功能。如果你想做更多自定义的事情,你也可以查看 Python 的 tokenize 库(只是觉得这很有趣)。
    【解决方案2】:

    您可以使用 the parse_expr() function in the module sympy.parsing.sympy_parser 将字符串转换为 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
    

    【讨论】:

    【解决方案3】:

    我意识到上面已经回答了这个问题,但是在获取带有未知符号的字符串表达式并需要访问这些符号的情况下,这是我使用的代码

    # 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)
    

    【讨论】:

      【解决方案4】:

      好吧,我知道eval邪恶的,但是如果您在程序中定义了 a、b 和 c,并且您可以确保执行 eval 是安全的,那么您不需要不需要同情。

      >>> a=5
      >>> b=5
      >>> c=2
      >>> exp = '(a+b)*40-(c-a)/0.5'
      >>> eval(exp)
      406.0
      

      【讨论】:

      • 我不明白为什么这个答案会被否决。它实现了 OP 的要求,同时也给出了警告。
      【解决方案5】:
      >>> 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多