Skip to content

Commit d051a34

Browse files
committed
Merge pull request #79 from drufat/numpy
Extending monte_carlo_pi example to support numpy
2 parents 7c134f3 + 2baa648 commit d051a34

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

examples/benchmarks/monte_carlo_pi.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,35 @@
1111

1212
from random import random
1313
from time import time
14-
from arrayfire import (array, randu)
1514
import arrayfire as af
1615
import sys
1716

17+
try:
18+
import numpy as np
19+
except:
20+
np = None
21+
1822
#alias range / xrange because xrange is faster than range in python2
1923
try:
2024
frange = xrange #Python2
2125
except NameError:
2226
frange = range #Python3
2327

24-
25-
def calc_pi_device(samples):
26-
x = randu(samples)
27-
y = randu(samples)
28-
return 4 * af.sum((x * x + y * y) < 1) / samples
29-
3028
# Having the function outside is faster than the lambda inside
3129
def in_circle(x, y):
3230
return (x*x + y*y) < 1
3331

32+
def calc_pi_device(samples):
33+
x = af.randu(samples)
34+
y = af.randu(samples)
35+
return 4 * af.sum(in_circle(x, y)) / samples
36+
37+
def calc_pi_numpy(samples):
38+
np.random.seed(1)
39+
x = np.random.rand(samples).astype(np.float32)
40+
y = np.random.rand(samples).astype(np.float32)
41+
return 4 * np.sum(in_circle(x, y)) / samples
42+
3443
def calc_pi_host(samples):
3544
count = sum(1 for k in frange(samples) if in_circle(random(), random()))
3645
return 4 * float(count) / samples
@@ -53,4 +62,6 @@ def bench(calc_pi, samples=1000000, iters=25):
5362
af.info()
5463

5564
bench(calc_pi_device)
65+
if np:
66+
bench(calc_pi_numpy)
5667
bench(calc_pi_host)

0 commit comments

Comments
 (0)