Math and Science with Python

Monte Carlo Simulation in Python with NumPy

Answer questions about chance by simulating them thousands of times: estimate pi and dice probabilities with random numbers.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • Seeded random numbers with default_rng
  • Estimating pi from random points
  • Probabilities by counting simulated outcomes
Estimates of pi
1,000
100,000
1,000,000
3.14800
3.13704
3.14201

Try it many times and count

Découvrez Monte Carlo Simulation in Python avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  1. np.random.default_rng(42) makes a seeded generator, so the results repeat.
  2. Points in the quarter circle land with probability pi / 4, so 4 * inside / n estimates pi.
  3. rng.integers(1, 7, size=(100_000, 2)) rolls two dice 100,000 times.
  4. np.mean(condition) is the share of trials where the condition is True.

Quand l’utiliser ?

  • Solve equations, integrals and differential equations in a few lines.
  • Fit models to measured data and analyse signals in science and engineering classes.
  • Check homework answers numerically and see where a hand calculation went wrong.

Code d’exemple

main.py
import numpy as np

rng = np.random.default_rng(42)

# Estimate pi: throw random points into a 1 x 1 square and count how many
# land inside the quarter circle x**2 + y**2 <= 1
for n in [1_000, 100_000, 1_000_000]:
    x = rng.random(n)
    y = rng.random(n)
    inside = np.count_nonzero(x**2 + y**2 <= 1)
    print(f"n = {n:>9,}  pi ~ {4 * inside / n:.5f}")

# Probability that two dice add up to 7 (exact answer 1/6 = 0.1667)
rolls = rng.integers(1, 7, size=(100_000, 2))
p_seven = np.mean(rolls.sum(axis=1) == 7)
print(f"P(sum = 7) ~ {p_seven:.4f}")

# Probability of at least one six in four rolls (exact 0.5177)
four = rng.integers(1, 7, size=(100_000, 4))
print(f"P(at least one 6 in 4 rolls) ~ {np.mean((four == 6).any(axis=1)):.4f}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

n =     1,000  pi ~ 3.14800
n =   100,000  pi ~ 3.13704
n = 1,000,000  pi ~ 3.14201
P(sum = 7) ~ 0.1676
P(at least one 6 in 4 rolls) ~ 0.5169

Explication du code

Cet exemple montre Monte Carlo Simulation in Python en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Outils pour cette leçon