使用 Numpyexp
代替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])
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