python - 使用 Sympy 实现用户输入的正确方法?

标签 python sympy

我目前正在创建一个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)

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

谢谢!

最佳答案

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 : = \n {diff(sympified, x)} \n derivative / y : \n {diff(sympified, y)}')

输出:

testinput: cos(y) + 2*x

derivate /x :
2
derivative /y :
-sin(y)

关于python - 使用 Sympy 实现用户输入的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74530358/

相关文章:

python - 如何避免 Sympify 自动去掉括号

python - 如何从 SymPy 符号表达式中删除 (1) 系数?

python - 屈服然后返回还是直接返回?

python - 如何绘制 sympy 微分与数组和循环方法?

python - 使用 OpenCV 进行 RaspiCam 鱼眼校准

python - 为什么 pandas.to_csv 为整数写 float ?

python - 如何访问 SymPy 中获得的线性方程组解?

python - 为什么 SymPy 在我对符号矩阵进行行归约时给出错误答案?

python - Python中2线性线搜索的效率差异

python - 如何使用子进程运行这个命令行语句?