Answers for "monte carlo calculate pi"

0

monte carlo calculate pi

'''Pi calculator using Monte Carlo'''
import numpy as np
import random
from tqdm import tqdm

ORIGIN = np.array((0,0))
RADIUS = 1
ITERATIONS = 10 ** 7
hits = 0
total = 0

def get_point_in_square(side):
    x = random.uniform(-side/2, side/2)
    y = random.uniform(-side/2, side/2)
    return np.array((x,y))

for i in tqdm(range(ITERATIONS)):
    point =  get_point_in_square(RADIUS * 2)
    if np.linalg.norm(ORIGIN - point) < RADIUS: #determines if point in circle
        hits += 1
    total += 1
    
print((hits/total)*4)
Posted by: Guest on August-11-2021

Python Answers by Framework

Browse Popular Code Answers by Language