Skip to content

Commit 9e32b6e

Browse files
author
Dzhelil Rufat
committed
Contribute numpy example.
1 parent 7c134f3 commit 9e32b6e

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

examples/benchmarks/monte_carlo_pi.py

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

1212
from random import random
1313
from time import time
14-
from arrayfire import (array, randu)
14+
import numpy as np
1515
import arrayfire as af
1616
import sys
1717

@@ -21,16 +21,21 @@
2121
except NameError:
2222
frange = range #Python3
2323

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-
3024
# Having the function outside is faster than the lambda inside
3125
def in_circle(x, y):
3226
return (x*x + y*y) < 1
3327

28+
def calc_pi_device(samples):
29+
x = af.randu(samples)
30+
y = af.randu(samples)
31+
return 4 * af.sum(in_circle(x, y)) / samples
32+
33+
def calc_pi_numpy(samples):
34+
np.random.seed(1)
35+
x = np.random.rand(samples)
36+
y = np.random.rand(samples)
37+
return 4 * np.sum(in_circle(x, y)) / samples
38+
3439
def calc_pi_host(samples):
3540
count = sum(1 for k in frange(samples) if in_circle(random(), random()))
3641
return 4 * float(count) / samples
@@ -53,4 +58,5 @@ def bench(calc_pi, samples=1000000, iters=25):
5358
af.info()
5459

5560
bench(calc_pi_device)
61+
bench(calc_pi_numpy)
5662
bench(calc_pi_host)

0 commit comments

Comments
 (0)