在arange上使用数学函数

Big*_* Al 1 python math numpy python-2.7

我有一个我想要应用于arange的函数:

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)))
Run Code Online (Sandbox Code Playgroud)

产生的错误如下:

`TypeError: only length-1 arrays can be converted to Python scalars`
Run Code Online (Sandbox Code Playgroud)

我使用的是Python 2.7.

这种pythonic方法看起来应该可行,但事实并非如此.fx根据公式,我需要做些什么才能包含相应的f(x)值?

谢谢.

mdm*_*dml 6

使用Numpy exp而不是math's:

>>> 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])
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)