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.
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
np.random.default_rng(42)makes a seeded generator, so the results repeat.- Points in the quarter circle land with probability pi / 4, so
4 * inside / nestimates pi. rng.integers(1, 7, size=(100_000, 2))rolls two dice 100,000 times.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}")
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.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
Outils pour cette leçon
- Générer des nombres aléatoires avec NumPyDans cette leçon, vous allez générer des entiers aléatoires reproductibles avec le générateur Generator de NumPy.
- Traceur de courbes en ligne : tracer des points et des fonctionsTracez des points, un tableau collé ou des fonctions comme sin(x) en ligne et téléchargez le graphique en PNG. Traceur gratuit qui vous donne aussi le code Python avec Matplotlib.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.