【问题标题】:Proper way to implement user input with Sympy?使用 Sympy 实现用户输入的正确方法?
【发布时间】:2022-11-22 18:41:18
【问题描述】:

我目前正在创建一个 python 脚本,它将根据用户输入的公式进行一系列计算;但是,它没有按预期工作?

我尝试了以下方法:

init_printing(use_unicode=True)

x, y = symbols('x y', real = True)
userinput = sympify(input("testinput: "))

x_diff = diff(userinput, x)

print(x_diff)

但是,这总是返回零,但是当我直接写输入时,例如

init_printing(use_unicode=True)

x, y = symbols('x y', real = True)
userinput = x**0.5+y

x_diff = diff(userinput, x)

print(x_diff)

它完美无缺地工作,我在这里做错了什么?

谢谢!

【问题讨论】:

    标签: python sympy


    【解决方案1】:

    sympify 函数中添加locals 参数会对您有所帮助。这是一个工作代码,基于你的:

    from sympy import *
    
    init_printing(use_unicode=True)
    
    x, y = symbols('x y', real = True)
    userinput = input("testinput: ")
    locals = {'x':x, 'y':y}
    sympified = sympify(userinput, locals=locals)
    print(f'derivate /x : = 
     {diff(sympified, x)} 
     derivative / y : 
     {diff(sympified, y)}')
    

    输出:

    testinput: cos(y) + 2*x
    
    derivate /x :
    2
    derivative /y :
    -sin(y)
    

    【讨论】:

    • 在文档 (docs.sympy.org/latest/modules/core.html) 中找到:为了识别字符串,可以将其导入命名空间字典并作为局部变量传递
    • 非常感谢!我发现文档很难理解。我现在明白它是如何工作的。
    猜你喜欢
    • 2020-12-18
    • 2023-03-17
    • 2013-07-31
    • 2021-04-14
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多