integrale_monte_carlo.py

Created by elodie-gamot

Created on June 24, 2022

401 Bytes

Approximation d’une intégrale par la méthode de Monte-Carlo. On s’intéresse à l’aire comprise sous la courbe représentative de la fonction f(x)=x**2 et entre les droites d’équation x=0 et x=1.


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

def f(x):
  return x**2
  
def graph(N):
  inside=0
  X=[i/100 for i in range(101)]
  Y=[f(x) for x in X]
  plot(X,Y)
  for i in range(N):
    x=random()
    y=random()
    if y<f(x):
      scatter(x,y,color="blue")
      inside+=1
    else:
      scatter(x,y,color="red")
  show()
  return inside/N

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.