Monte Carlo & Stochastic Simulation

Monte Carlo & Stochasticbeginner~8 min

Estimate pi, compute integrals, and run a random walk using random sampling techniques.

Step 1 — Estimate pi with random darts

Throw random points at a unit square. Those that land inside the quarter-circle (x²+y²≤1) approximate the area π/4. Multiply the ratio by 4 to estimate π.

N = 100000;
x = rand(1, N); y = rand(1, N);
inside = sum(x.^2 + y.^2 <= 1);
pi_est = 4 * inside / N;
printf('Pi estimate: %.4f (error: %.4f)\n', pi_est, abs(pi_est - pi))
▶ Run in SimLab

Expected output: Pi estimate near 3.1416, error < 0.01

Step 2 — Monte Carlo integration

Estimate ∫₀¹ √(1−x²) dx (= π/4) by sampling uniformly and averaging the integrand. This generalises to high-dimensional integrals where quadrature is impractical.

N = 50000;
x = rand(1, N);
f = sqrt(1 - x.^2);
integral_est = mean(f);
printf('Integral estimate: %.4f (pi/4 = %.4f)\n', integral_est, pi/4)
▶ Run in SimLab

Expected output: Integral estimate close to 0.7854 (= pi/4)

Step 3 — Random walk

A 1D random walk adds +1 or -1 at each step with equal probability. Plotting many walks shows the diffusion envelope growing as √t.

steps = 500;
walks = 5;
hold on;
for k = 1:walks
  r = 2*(rand(1, steps) > 0.5) - 1;
  pos = cumsum(r);
  plot(1:steps, pos);
end
xlabel('Step'); ylabel('Position');
title('1D Random Walks')
▶ Run in SimLab

Expected output: Five random walk paths diverging from the origin

Related Tutorials

Try SimLab — Free MATLAB® Alternative

466 functions. Runs in your browser. No install.

Open SimLab

Stay Updated

Get notified about new simulations and tools. We send 1-2 emails per month.