# Tactiverge Academy — companion code for "Monte Carlo simulation and randomness"
# Lesson: https://tactiverge.win/academy/computational-engineering/scientific-simulation/monte-carlo-simulation/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
import math
import random

random.seed(2024)

def estimate_pi(n):
    inside = 0
    for _ in range(n):
        x, y = random.random(), random.random()
        if x * x + y * y <= 1.0:
            inside += 1
    return 4 * inside / n

for n in [100, 10_000, 1_000_000]:
    est = estimate_pi(n)
    print(f"N = {n:>9,}   estimate = {est:.5f}   error = {est - math.pi:+.5f}")


# ── Example 2 ────────────────────────────────────────
import math
import random
import statistics

random.seed(7)
# Made-up measurements for illustration: a simple pendulum
L_MEAN, L_SD = 1.000, 0.005   # length, m
T_MEAN, T_SD = 2.006, 0.010   # period, s

samples = []
for _ in range(100_000):
    L = random.gauss(L_MEAN, L_SD)
    T = random.gauss(T_MEAN, T_SD)
    samples.append(4 * math.pi**2 * L / T**2)

g_mean = statistics.mean(samples)
g_sd = statistics.stdev(samples)
print(f"g = {g_mean:.3f} ± {g_sd:.3f} m/s² (Monte Carlo, 100,000 samples)")

# Compare with the usual first-order formula for relative uncertainty
g0 = 4 * math.pi**2 * L_MEAN / T_MEAN**2
rel = math.sqrt((L_SD / L_MEAN) ** 2 + (2 * T_SD / T_MEAN) ** 2)
print(f"g = {g0:.3f} ± {g0 * rel:.3f} m/s² (formula)")


# ── Example 3 ────────────────────────────────────────
import math
import random
import statistics

random.seed(5)
G, RHO, MASS = 9.81, 1.2, 0.0027
AREA = math.pi * 0.020 ** 2

def drop_time(cd, height=10.0, dt=0.001):
    t, y, v = 0.0, 0.0, 0.0
    while y < height:
        a = G - 0.5 * RHO * cd * AREA * v * v / MASS
        y, v, t = y + v * dt, v + a * dt, t + dt
    return t

# Assumption for illustration: Cd is 0.47 give or take 0.05 (one sd)
times = [drop_time(random.gauss(0.47, 0.05)) for _ in range(1000)]
times.sort()
print(f"mean landing time: {statistics.mean(times):.3f} s")
print(f"sd:                {statistics.stdev(times):.3f} s")
print(f"middle 95%:        {times[25]:.3f} s to {times[974]:.3f} s")
