montecarlo.py

Created by francoise-cavanne

Created on June 09, 2020

824 Bytes


from math import *
from random import random,randint
from matplotlib.pyplot import *
def montecarlo_graph(N):
    Q=0
    listebleuX=[]
    listebleuY=[]
    listerougeX=[]
    listerougeY=[]
    for i in range(1,N-1):
        x=random()
        y=random()
        if x**2+y**2 <1:
            listebleuX.append(x)
            listebleuY.append(y)
            Q=Q+1
        else:
            listerougeX.append(x)
            listerougeY.append(y)
    axis((0,1,0,1))
    grid()
    listeX=[x/300 for x in range(301)]
    listeY=[sqrt(1-x**2) for x in listeX]
    plot(listeX,listeY,"k.",ms=4)
    plot(listebleuX,listebleuY,"b.",ms=4)
    plot(listerougeX,listerougeY,"r.",ms=4)
    titre="approximation de pi avec "+str(N)+" points : "+str(4*Q/N)
    title(titre)
    show()
    return ("fin", 4*Q/N)