Closed
Description
import numpy as np
import time
BATCH_SIZE = 2048 # Draw random pairs (x, y) in batches of BATCH_SIZE elements
N_BATCHES = 1024 # Total number of batches
N = N_BATCHES * BATCH_SIZE # Total number of random pairs (x, y)
def monte_carlo_pi_batch():
x = np.random.random(BATCH_SIZE)
y = np.random.random(BATCH_SIZE)
acc = np.count_nonzero(x * x + y * y <= 1.0)
return 4.0 * acc / BATCH_SIZE
def monte_carlo_pi():
s = 0.0
for i in range(N_BATCHES):
s += monte_carlo_pi_batch()
return s/N_BATCHES
def main():
print("Using device ...")
t1 = time.time()
pi = monte_carlo_pi()
t2 = time.time()
print("Pi =", pi)
print("Done in ", t2 - t1, "seconds...")
if __name__ == "__main__":
main()