Write a program to caclulate the approximate value of pi using the monte carlo method


Topic: Write a program to caclulate the approximate value of pi using the monte carlo method

Solution

import random
def pi_monte_carlo(n=1000000):
    count = 0
    for _ in range(n):
        x = random.random()
        y = random.random()
        if x ** 2 + y ** 2 <= 1:
            count += 1
    return 4 * count / n
print(pi_monte_carlo())



List all Python Programs