Approximating pi with the Monte Carlo method gives suprisingly accurate results

120 Views Asked by At

I am trying to apply the Monte Carlo method to obtain an approximate value of π but I am a little surprised by the results I obtained because it seemed to me that with 539,354 points drawn, I was supposed to get an approximate value of π to within 10–2. But I get much better precision and so I wonder if I made a mistake somewhere in my code or if it actually takes fewer draws to get an accuracy of one hundredth.

Here is my Python code:

from random import random
from math import pi
import numpy
from numpy.random import rand
 
 
def simulX():
    x, y = random(), random()
    return int(x**2 + y**2 <= 1)
 
def calculer_Sn(n=1000):
    x = rand(n)
    y = rand(n)
    return numpy.sum(x**2 + y**2 <= 1)
 
def calculer_Pn(n=1000):
    return 4 * calculer_Sn(n) / n
 
def approxpi():
    return calculer_Pn(539354)
 
print(sum(abs(approxpi() - pi) for x in range(1000)) / 1000)

Over 1000 tests, we obtain, probably, on average, a deviation from π very much lower than 10–2.

0

There are 0 best solutions below