要“矢量化”使用numpy
,这意味着不是像这样进行显式循环,
for i in range(1, n):
c = c + f(i)
然后你应该把i
它做成一个 numpy 数组,然后简单地取它的总和:
i = np.arange(1,n)
c = i.sum()
numpy 会自动为您进行矢量化。这更快的原因是由于各种原因,numpy 循环以比普通 python 循环更好的优化方式完成。一般来说,循环/数组越长,优势就越大。这是您实现的梯形积分:
import numpy as np
def f1(x):
return 2*x + 1
# Here's your original function modified just a little bit:
def integ(f,a,b,n):
h = (b-a)/n
a1 = (h/2)*f(a)
b1 = (h/2)*f(b)
c1 = 0
for i in range(1,n,1):
c1 = f((a+i*h))+c1
return a1 + b1 + h*c1
# Here's the 'vectorized' function:
def vinteg(f, a, b, n):
h = (b-a) / n
ab = 0.5 * h * (f(a)+f(b)) #only divide h/2 once
# use numpy to make `i` a 1d array:
i = np.arange(1, n)
# then, passing a numpy array to `f()` means that `f` returns an array
c = f(a + h*i) # now c is a numpy array
return ab + c.sum() # ab + np.sum(c) is equivalent
在这里,我将把我命名的内容导入tmp.py
到ipython
会话中,以便比使用更容易计时time.time
:
import trap
f = trap.f1
a = 0
b = 100
n = 1000
timeit trap.integ(f, a, b, n)
#1000 loops, best of 3: 378 us per loop
timeit trap.vinteg(f, a, b, n)
#10000 loops, best of 3: 51.6 us per loop
哇,快七倍。
看看它是否对较小的人有很大帮助n
n = 10
timeit trap.integ(f, a, b, n)
#100000 loops, best of 3: 6 us per loop
timeit trap.vinteg(f, a, b, n)
#10000 loops, best of 3: 43.4 us per loop
不,小循环要慢得多!非常大n
呢?
n = 10000
timeit trap.integ(f, a, b, n)
#100 loops, best of 3: 3.69 ms per loop
timeit trap.vinteg(f, a, b, n)
#10000 loops, best of 3: 111 us per loop
快三十倍!