monte carlo calculate pi

Solutions on MaxInterview for monte carlo calculate pi by the best coders in the world

showing results for - "monte carlo calculate pi"
Anna
07 Jan 2019
1'''Pi calculator using Monte Carlo'''
2import numpy as np
3import random
4from tqdm import tqdm
5
6ORIGIN = np.array((0,0))
7RADIUS = 1
8ITERATIONS = 10 ** 7
9hits = 0
10total = 0
11
12def get_point_in_square(side):
13    x = random.uniform(-side/2, side/2)
14    y = random.uniform(-side/2, side/2)
15    return np.array((x,y))
16
17for i in tqdm(range(ITERATIONS)):
18    point =  get_point_in_square(RADIUS * 2)
19    if np.linalg.norm(ORIGIN - point) < RADIUS: #determines if point in circle
20        hits += 1
21    total += 1
22    
23print((hits/total)*4)