Skip to main content
 首页 » 编程设计

python之在 arange 上使用数学函数

2025年05月04日9arxive

我有一个函数要应用于排列:

import math 
from numpy import arange 
x = arange(7.0,39.0,0.0001) 
fx = math.exp(-2.0 / (-14.4 + 19.33 * x - 0.057 * pow(x,2))) 

产生的错误如下:

`TypeError: only length-1 arrays can be converted to Python scalars` 

我正在使用 Python 2.7。

这种 pythonic 方法似乎应该有效,但实际上没有。根据等式,我需要做什么才能使 fx 包含相应的 f(x) 值?

谢谢。

请您参考如下方法:

使用 Numpy 的 exp而不是 math 的:

>>> from numpy import arange, exp 
>>> x = arange(7.0,39.0,0.0001) 
>>> fx = exp(-2.0 / (-14.4 + 19.33 * x - 0.057 * pow(x,2))) 
>>> fx 
array([ 0.98321018,  0.98321044,  0.98321071, ...,  0.99694082, 
        0.99694082,  0.99694083]) 

Numpy 的版本与 Numpy ndarrays 配合得很好,例如 x。它还具有 Numpy 的性能优势,在本例中与 vectorize 相比是一个数量级。 math.exp 解法:

# built-in Numpy function 
In [5]: timeit exp(-2.0 / (-14.4 + 19.33 * x - 0.057 * pow(x,2))) 
100 loops, best of 3: 10.1 ms per loop 
# vectorized math.exp function 
In [6]: fx = np.vectorize(lambda y: math.exp(-2.0 / (-14.4 + 19.33 *  - 0.057 * pow(y,2)))) 
In [7]: timeit fx(x) 
1 loops, best of 3: 221 ms per loop