monte_carlo.py

Created by alain-busser

Created on June 24, 2019

599 Bytes

Méthode de Monte-Carlo pour calculer l’aire sous un cercle ou une parabole (programme de 1ère à partir de la rentrée 2019). Pour estimer π/4, lancer la fonction monte_carlo_cercle(N) avec N assez grand; pour estimer l’aire sous la parabole, lancer monte_carlo_parabole(N) avec N assez grand.


from kandinsky import *
from math import *
from random import *
rouge = color(255,0,0)
bleu = color(0,0,255)
def point_rouge(x,y):
  set_pixel(int(200*x),int(200-200*y),rouge)
def point_bleu(x,y):
  set_pixel(int(200*x),int(200-200*y),bleu)
def monte_carlo(f,N):
  S = 0
  for k in range(N):
    (x,y) = (random(),random())
    if y < f(x):
      S += 1
      point_rouge(x,y)
    else:
      point_bleu(x,y)
  draw_string(str(S/N),0,200)
def monte_carlo_cercle(N):
  return monte_carlo(lambda x: sqrt(1-x**2),N)
def monte_carlo_parabole(N):
  return monte_carlo(lambda x: x**2,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.