如何用python numpy vectorization解决这个练习?

时间:2013-04-05 13:34:36

标签: numpy

如何使用python Numpy矢量化解决第2页的练习4.5?

下载链接:

https://dl.dropbox.com/u/92795325/Python%20Scripting%20for%20Computational%20Scien%20-%20H.P.%20%20Langtangen.pdf

我用Python循环尝试了这个,但我需要Vectorization版本。

from numpy import *
import time

def fun1(x):
       return 2*x+1

def integ(a,b,n):
       t0 = time.time()
       h = (b-a)/n
       a1 = (h/2)*fun1(a)
       b1 = (h/2)*fun1(b)
       c1 = 0
       for i in range(1,n,1):
              c1 = fun1((a+i*h))+c1
       t1 = time.time()
       return a1+b1+h*c1, t1-t0

1 个答案:

答案 0 :(得分:0)

使用numpy “vectorize”,所有这些意味着不是像

那样进行显式循环
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

在这里,我将{I} 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

快30倍!