Information, calcul, communication

CS-119(k)

ICC-P Série 8 Corrigé

This page is part of the content downloaded from ICC-P Série 8 Corrigé on Sunday, 29 June 2025, 20:43. Note that some content and any files larger than 50 MB are not downloaded.

Page content

Code:
from random import random def random_estimate(nb_points: int) -> float: count_inside = 0 start = -1 side = 2 for _ in range(nb_points): # Par simplicité, on place le centre en 0,0 x = start + side * random() y = start + side * random() if (x**2 + y**2) < 1: count_inside += 1 return 4 * count_inside / nb_points for c in [100, 1000, 10000]: for reapeat in range(5): print(f"random_estimate({c}) me donne: {random_estimate(c)}") # On observe que cet algorithme estime la valeur de pi: # Plus le nombre de points est élevé, plus l'estimation est précise. def grid_estimate(n: int) -> float: count_inside = 0 sub_square_side = 2/n for i in range(n): start_x = (2 * i / n) - 1 for j in range(n): start_y = (2 * j / n) - 1 x = start_x + sub_square_side * random() y = start_y + sub_square_side * random() if x ** 2 + y ** 2 < 1: count_inside += 1 return 4 * count_inside / ( n * n ) for n in [10, 32, 100]: for reapeat in range(5): print(f"grid_estimate({n}) me donne: {grid_estimate(n)}") # On remarque que la version grille est plus précise pour le même nombre de points. # Par exemple: grid_estimate(100) est souvent plus précis que random_estimate(10000)