Skip to main content
 首页 » 编程设计

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

2025年05月04日13yxwkf

我希望我的程序的用户以 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 

使用上面的代码,用户正在输入指数函数,该函数被保存到变量“f”中——更一般地说,我希望任何数学函数作为输入给出,并以某种方式存储为 python功能。伪代码可能是这样的:

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

如果我们再次使用指数函数作为示例,则相当于硬编码:

def F(x): 
    return np.exp(x) 

为清楚起见,再举一个例子。

def F(x): 
    f = eval(input("Please enter function in numpy notation:")) 
    return f 
 
>>> x*np.sin(x) 

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

def F(x): 
    return x*np.sin(x) 

有什么办法吗?

请您参考如下方法:

考虑使用 numexpr module .

例子:

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

它通常也比 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)