how to solve this exercise with python numpy vectorization? -
how solve exercise 4.5 on page 2 python numpy vectorization?
link download:
i tried python loop, need vectorization version.
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 in range(1,n,1): c1 = fun1((a+i*h))+c1 t1 = time.time() return a1+b1+h*c1, t1-t0
to "vectorize" using numpy
, means instead of doing explicit loop like,
for in range(1, n): c = c + f(i)
then instead should make i
numpy array, , take sum:
i = np.arange(1,n) c = i.sum()
and numpy automatically vectorization you. reason faster because numpy loops done in better optimized way plain python loop, variety of reasons. speaking, longer loop/array, better advantage. here trapezoidal integration implemented:
import numpy np def f1(x): return 2*x + 1 # here's original function modified little bit: def integ(f,a,b,n): h = (b-a)/n a1 = (h/2)*f(a) b1 = (h/2)*f(b) c1 = 0 in range(1,n,1): c1 = f((a+i*h))+c1 return a1 + b1 + h*c1 # here's '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 make `i` 1d array: = np.arange(1, n) # then, passing numpy array `f()` means `f` returns array c = f(a + h*i) # c numpy array return ab + c.sum() # ab + np.sum(c) equivalent
here import named tmp.py
ipython
session easier timing using time.time
:
import trap f = trap.f1 = 0 b = 100 n = 1000 timeit trap.integ(f, a, b, n) #1000 loops, best of 3: 378 per loop timeit trap.vinteg(f, a, b, n) #10000 loops, best of 3: 51.6 per loop
wow, 7 times faster.
see if helps smaller n
n = 10 timeit trap.integ(f, a, b, n) #100000 loops, best of 3: 6 per loop timeit trap.vinteg(f, a, b, n) #10000 loops, best of 3: 43.4 per loop
nope, slower small loops! large 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 per loop
thirty times faster!
Comments
Post a Comment