Skip to main content

5.5b Monte Carlo integration labs

Source: Lab ideas from Computational Physics (Landau, Páez, Bordeianu), §5.5. Rewritten as original drills. Continues 5.5 Monte Carlo integration.

Estimate π\pi by stone throwing and ∫01e−x dx\int_0^1 e^{-x}\,dx by mean-value Monte Carlo. Graded randomness uses the chapter LCG only — not random.random().

Fixed LCG

r ← (1103515245 * r + 12345) % 2**31, then uniform r / 2**31. Default seed is 1 unless the prompt says otherwise. Advance the state before each draw (seed itself is not a sample).

Formula refresh​

Warm up: pick the matching equation among lookalikes (same walk as the theory lesson).

Labs​

Activity: Stone-throw π\pi (N=10000N=10000)

Draw NN points uniformly in [−1,1]2[-1,1]^{2} with the chapter LCG (seed 11). Count hits with x2+y2≤1x^{2}+y^{2}\le 1. Print

4 * hits / N

with 6 decimals.

No input. Use N=10000N=10000.

Write-ups​

0/4 solved
5.5b.W1

Using “fraction”, “area”, and “box”, explain:

In one sentence: how does stone throwing estimate a pond’s area?

Minimum 3 words. Your answer must include: “fraction”, “area”, “box”.

0 words/ 3 min

Meet the writing requirements, then you can open the model answer.

Explorers​

# mc_stone.py — chapter LCG stone throw (original sketch)
M = 2**31

def rnd(r):
r = (1103515245 * r + 12345) % M
return r, r / M

def pi_est(N, seed=1):
r, hits = seed, 0
for _ in range(N):
r, u = rnd(r)
r, v = rnd(r)
x, y = 2 * u - 1, 2 * v - 1
if x * x + y * y <= 1:
hits += 1
return 4 * hits / N

Next: 5.6 Mean-value theorem and high-D Monte Carlo.