forked from arrayfire/arrayfire-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonte_carlo_pi.py
More file actions
executable file
·67 lines (54 loc) · 1.76 KB
/
monte_carlo_pi.py
File metadata and controls
executable file
·67 lines (54 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/python
#######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
########################################################
from random import random
from time import time
import arrayfire as af
import sys
try:
import numpy as np
except:
np = None
#alias range / xrange because xrange is faster than range in python2
try:
frange = xrange #Python2
except NameError:
frange = range #Python3
# Having the function outside is faster than the lambda inside
def in_circle(x, y):
return (x*x + y*y) < 1
def calc_pi_device(samples):
x = af.randu(samples)
y = af.randu(samples)
return 4 * af.sum(in_circle(x, y)) / samples
def calc_pi_numpy(samples):
np.random.seed(1)
x = np.random.rand(samples).astype(np.float32)
y = np.random.rand(samples).astype(np.float32)
return 4. * np.sum(in_circle(x, y)) / samples
def calc_pi_host(samples):
count = sum(1 for k in frange(samples) if in_circle(random(), random()))
return 4 * float(count) / samples
def bench(calc_pi, samples=1000000, iters=25):
func_name = calc_pi.__name__[8:]
print("Monte carlo estimate of pi on %s with %d million samples: %f" % \
(func_name, samples/1e6, calc_pi(samples)))
start = time()
for k in frange(iters):
calc_pi(samples)
end = time()
print("Average time taken: %f ms" % (1000 * (end - start) / iters))
if __name__ == "__main__":
if (len(sys.argv) > 1):
af.set_device(int(sys.argv[1]))
af.info()
bench(calc_pi_device)
if np:
bench(calc_pi_numpy)
bench(calc_pi_host)