获取数学函数作为用户输入 [英] Getting mathematical function as user's input
问题描述
我需要知道如何将字符串输入转换为可执行函数. 例如-用户编写字符串'x * Sin(x ** 2)',然后programm将其用作函数,可以为给定的x计算值,可以绘制此函数的派生等. scitools.stringfunction,但据我所知,此模块在python-3中不可调用.
I need to know how transfer string input into executable function. For example - user write string 'x*Sin(x**2)' and then programm takes it as function, can calculate a value for given x, can plot derivation of this function etc. I've read that there is module called scitools.stringfunction, but as far as I know this module is not callable in python-3.
任何想法如何实现?
推荐答案
像这样:
from sympy import var
from sympy import sympify
x = var('x') # the possible variable names must be known beforehand...
user_input = 'x * sin(x**2)'
expr = sympify(user_input)
res = expr.subs(x, 3.14)
print(res) # -1.322...
如果要将用户输入转换为函数,可以调用此函数:
if you want to turn the user input into a function you can call you could to this:
from sympy.utilities.lambdify import lambdify
f = lambdify(x, expr)
# f(3.14) -> -1.322...
sympy可以进行符号计算(包括导数);如果要绘制图,我强烈建议 matplotlib
.
sympy can do sybolic calculations (including derivatives); if you want to make plots i strongly suggest matplotlib
.
使用与 eval
相对的数学库的优点是您不需要清理用户输入(针对恶意代码).
(由于 ejm 的评论而删除了此内容.)
the advantage of using a math library opposed to eval
is that you do not need to sanitize the user input (against malicious code).
(deleted this thanks to a comment from ejm).
这篇关于获取数学函数作为用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!