Skip to content

Commit 6c830db

Browse files
committed
added numpy version
1 parent 7f1c19c commit 6c830db

File tree

4 files changed

+54
-19
lines changed

4 files changed

+54
-19
lines changed

source/examples/threading-multiprocessing/integrate/integrate.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,24 @@ def integrate(f, a, b, N):
1010
return s * dx
1111

1212

13-
def integrate_f_with_functional_tools(a, b, N):
14-
dx = (float(b) - a) / N
13+
def integrate_f_with_functional_tools(f, a, b, N):
14+
dx = (b - a) / N
1515
return sum(map(f, ((a + y * dx) for y in range(N)))) * dx
16+
17+
18+
def integrate_numpy(f, a, b, N):
19+
"""
20+
numpy can be used to "vectorize" the problem
21+
22+
f must be "numpy comaptible"
23+
24+
"""
25+
# imported here so the rest of the code can run without it
26+
import numpy as np
27+
dx = (b - a) / N
28+
i = np.arange(N)
29+
s = np.sum(f(a + (i * dx)))
30+
return s * dx
31+
32+
33+

source/examples/threading-multiprocessing/integrate_main_profiler.py

Lines changed: 0 additions & 17 deletions
This file was deleted.
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#!/usr/bin/env python3
2+
3+
from integrate.integrate import (f,
4+
integrate_numpy as _integrate_numpy,
5+
integrate as _integrate
6+
)
7+
from decorators import timer
8+
9+
10+
@timer
11+
def integrate(*args):
12+
return _integrate(*args)
13+
14+
15+
a = 0.0
16+
b = 10.0
17+
18+
print("running the pure python version")
19+
for N in (10**i for i in range(1, 8)):
20+
print("Numerical solution with N=%(N)d : %(x)f" %
21+
{'N': N, 'x': integrate(f, a, b, N)})
22+
23+
24+
# now the numpy version:
25+
@timer
26+
def integrate_numpy(*args):
27+
return _integrate_numpy(*args)
28+
29+
30+
print("running the numpy version")
31+
for N in (10**i for i in range(1, 8)):
32+
print("Numerical solution with N=%(N)d : %(x)f" %
33+
{'N': N, 'x': integrate_numpy(f, a, b, N)})

source/examples/threading-multiprocessing/integrate_threads.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
# sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
77

88
from integrate.integrate import integrate, f
9+
# from integrate.integrate import f, integrate_numpy as integrate
910
from decorators import timer
1011

1112

0 commit comments

Comments
 (0)