comparerecmontecarlo.py

Created by christian-mercat

Created on January 06, 2025

809 Bytes

Compare le calcul de pi/4 par la méthode de Montecarlo (tirage aléatoire d’un point du carré unité et proportion de points dans le disque) et la méthode des rectangles sur sqrt(1-x**2) de 0 à 1. La comparaison est le nombre de boucles.


from math import *
from random import *
from matplotlib.pyplot import *

def rec(f=lambda x: sqrt(1-x**2),a=0,b=1,n=10000
,gd=0):
  # Calcul de l'intégrale de la fonction f, entre a et b, avec n rectangles, au point gd=0: gauche, gd=0.5: milieu, gd=1: droite
  d=(b-a)/n
  xi=a+gd*d
  s = 0
  for _i in range(n):
    s += f(xi)
    xi += d
  return s*d

def disque(x,y)->boolean:
  # Un booléen qui dit si (x,y)∈ disque unité
  return x**2+y**2 <1

def montecarlo(n=1000):
  # Calcul de l'aire du quart de disque unité par la méthode de Montecarlo
  s=0
  for _i in range(n):
    if disque(random(),random()) :
      s += 1
  return s/n

N=10
X=[2**i for i in range(N)]
Ym=[montecarlo(n=X[i]) for i in range(N)]
Yr=[rec(n=X[i]) for i in range(N)]

plot(X,Ym)
plot(X,Yr)
show()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.