monte_carlo.py

Created by alain-busser

Created on June 25, 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)