Monte Carlo simulation helps us understand uncertain situations by trying many random examples. It shows possible outcomes and their chances.
0
0
Monte Carlo simulation basics in NumPy
Introduction
Estimating the chance of winning a game with random moves.
Predicting future sales when customer behavior is uncertain.
Calculating the risk of investment portfolios with many unknown factors.
Finding the area of a shape that is hard to measure exactly.
Syntax
NumPy
import numpy as np # Step 1: Generate many random samples samples = np.random.random(size=N) # Step 2: Apply a function or condition to samples results = some_function(samples) # Step 3: Calculate statistics like mean or probability estimate = np.mean(results)
np.random.random(size=N) creates N random numbers between 0 and 1.
You can replace some_function with any calculation or test you want to simulate.
Examples
This example estimates the average of random numbers between 0 and 1, which should be close to 0.5.
NumPy
import numpy as np N = 10000 samples = np.random.random(size=N) estimate = np.mean(samples) print(estimate)
This example estimates the value of π by checking how many random points fall inside a quarter circle.
NumPy
import numpy as np N = 100000 samples_x = np.random.random(size=N) samples_y = np.random.random(size=N) inside_circle = (samples_x**2 + samples_y**2) < 1 pi_estimate = 4 * np.mean(inside_circle) print(pi_estimate)
Sample Program
This program uses Monte Carlo simulation to estimate π. It randomly picks points in a square and counts how many fall inside a quarter circle. The ratio helps estimate π.
NumPy
import numpy as np # Number of random trials N = 100000 # Generate random points in the square [0,1] x [0,1] x = np.random.random(size=N) y = np.random.random(size=N) # Check if points fall inside the quarter circle of radius 1 inside_circle = (x**2 + y**2) <= 1 # Estimate pi using the ratio of points inside the circle pi_estimate = 4 * np.mean(inside_circle) print(f"Estimated value of pi: {pi_estimate:.5f}")
OutputSuccess
Important Notes
More trials (larger N) give better estimates but take more time.
Monte Carlo simulation works well when exact math is hard or impossible.
Randomness means results will be slightly different each time you run the code.
Summary
Monte Carlo simulation uses random sampling to estimate results.
It is useful for problems with uncertainty or complex math.
Using numpy makes it easy to generate many random samples quickly.