import time
from numba import autojit
from numba import random
from math import sqrt
state = random.state_p
PREC = 0xffffffff
@autojit
def myhypot(a, b):
return sqrt(a*a + b*b)
@autojit
def rand():
return random.rk_interval(PREC, state) / PREC
@autojit
def myPi (nt):
count_inside = 0
for c in range(0, nt):
if myhypot(rand(), rand()) < 1:
count_inside += 1
return 4.0 * count_inside / nt
myPi(100)
tic = time.clock()
print myPi(10000000)
print time.clock() - tic
function myPi(nt)
count_inside = 0 for c in 1:nt if (hypot(rand(), rand()) < 1) count_inside += 1 end end return 4.0 * count_inside / nt end
myPi(100)
@time myPi(10000000)
function montepi(n)
s = 0
for i = 1:n
s += rand()^2 + rand()^2 < 1
end
return 4*s/n
end
julia> function myPi1(nt)
count_inside = 0for c in 1:nt
if hypot(rand(),rand()) < 1
count_inside += 1endendreturn 4.0 * count_inside / ntend
myPi1 (generic function with 1 method)julia> @time myPi1(1000000)elapsed time: 0.171592815 seconds (64 bytes allocated)3.14142julia> myhypot(x,y) = sqrt(x*x + y*y)myhypot (generic function with 1 method)julia> function myPi2(nt)
count_inside = 0for c in 1:nt
if myhypot(rand(),rand()) < 1
count_inside += 1endendreturn 4.0 * count_inside / ntend
myPi2 (generic function with 1 method)julia> @time myPi2(1000000)elapsed time: 0.155481895 seconds (64 bytes allocated)3.144868
julia> function myPi3(nt)
count_inside = 0for c in 1:nt
if sqrt(rand()^2 + rand()^2) < 1
count_inside += 1endendreturn 4.0 * count_inside / ntend
myPi3 (generic function with 1 method)julia> @time myPi3(1000000)elapsed time: 0.154946413 seconds (64 bytes allocated)3.142644
julia> function myPi4(nt)
count_inside = 0for c in 1:nt
if rand()^2 + rand()^2 < 1
count_inside += 1endendreturn 4.0 * count_inside / ntend
myPi4 (generic function with 1 method)julia> @time myPi4(1000000)elapsed time: 0.100211371 seconds (64 bytes allocated)3.141872
myPi1 = 0.171592815 = 1.00 * myPi1myPi2 = 0.155481895 = 0.91 * myPi1myPi3 = 0.154946413 = 0.90 * myPi1myPi4 = 0.100211371 = 0.58 * myPi1