File: monte_carlo_pi.py

package info (click to toggle)
python-arrayfire 3.3.20160624-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 764 kB
  • ctags: 826
  • sloc: python: 3,999; makefile: 205
file content (56 lines) | stat: -rwxr-xr-x 1,541 bytes parent folder | download
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
#!/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
from arrayfire import (array, randu)
import arrayfire as af
import sys

#alias range / xrange because xrange is faster than range in python2
try:
    frange = xrange  #Python2
except NameError:
    frange = range   #Python3


def calc_pi_device(samples):
    x = randu(samples)
    y = randu(samples)
    return 4 * af.sum((x * x  + y * y) < 1) / samples

# Having the function outside is faster than the lambda inside
def in_circle(x, y):
    return (x*x + y*y) < 1

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)
    bench(calc_pi_host)