如何使用'input'在python 3.x中输入数学函数作为变量

PyR*_*red 1 python numpy input

我希望我的程序的用户以numpy表示法输入他们选择的数学函数,以便我可以对它进行操作.例如:

import numpy as np
f=eval(input("Please input your function in numpy notation")

>>> "Please input your function in numpy notation"
>>> np.exp(x)
>>> NameError: name 'x' is not defined
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,用户输入指数函数,该函数保存到变量'f' - 更一般地说,我希望任何数学函数都作为输入给出,并且它以某种方式存储为python函数.伪代码可能是这样的:

def F(x):
    f = eval(input("Please enter function in numpy notation:"))
    return f
Run Code Online (Sandbox Code Playgroud)

如果我们再次使用指数函数作为例子,它将等同于硬编码:

def F(x):
    return np.exp(x)
Run Code Online (Sandbox Code Playgroud)

为清晰起见,还有一个例子

def F(x):
    f = eval(input("Please enter function in numpy notation:"))
    return f

>>> x*np.sin(x)
Run Code Online (Sandbox Code Playgroud)

用户在命令行输入x*np.sin(x),相当于硬编码:

def F(x):
    return x*np.sin(x)
Run Code Online (Sandbox Code Playgroud)

反正有没有这样做?

Max*_*axU 5

考虑使用numexpr模块.

例:

In [23]: import numexpr as ne

In [24]: a = np.arange(1e6)

In [25]: s = "sin(a)**2 + cos(a)**2"

In [27]: res = ne.evaluate(s)

In [28]: res
Out[28]: array([ 1.,  1.,  1., ...,  1.,  1.,  1.])

In [29]: res.shape
Out[29]: (1000000,)
Run Code Online (Sandbox Code Playgroud)

它通常比Numpy快:

In [32]: %timeit ne.evaluate(s)
11.4 ms ± 256 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [33]: %timeit np.sin(a)**2 + np.cos(a)**2
41 ms ± 1.15 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Run Code Online (Sandbox Code Playgroud)