Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 45 ยท Real-World Projects

Project: Monte Carlo Estimates

Estimate pi, simulate random walks and price an option-style payoff with vectorized Monte Carlo in MATLAB and Octave, and see error shrink with sample size.

Some quantities are hard to compute exactly but easy to simulate. A Monte Carlo method estimates them by generating many random samples and averaging. It is slow compared with a formula, but it works for problems where no formula exists: queues, particle paths, financial products with awkward rules.

In this project you estimate pi from random points, follow a cloud of random walkers, estimate the expected payoff of an option-like contract, and finally measure how fast the error falls as you add samples. The code is vectorized from the start (see Vectorization): every simulation draws all of its random numbers in one matrix instead of looping. MATLAB and Octave do not run in your browser here, so the MATLAB code is read-only. Each step has a runnable NumPy stand-in. The random numbers differ between MATLAB and NumPy, so your digits will differ from those printed here, but the behaviour is identical.

Monte Carlo in three moves

Sample Draw many random inputs at once.
Evaluate Apply the rule to every sample.
Average The mean is the estimate.
1 / 2

Step 1: estimating pi

Throw random points into the square from (0, 0) to (1, 1). The quarter circle of radius 1 covers an area of pi/4 inside it, so the fraction of points with x^2 + y^2 < 1 should be about pi/4. Multiply by 4:

MATLAB
rng(7)
N = 1e6;
x = rand(N, 1);
y = rand(N, 1);
inside = (x.^2 + y.^2) < 1;        % logical vector
pi_est = 4 * mean(inside)

There is no loop. rand(N,1) makes a million numbers at once, the comparison produces a logical vector, and mean of a logical vector is the fraction of true values (see Logical Indexing and find). A million points need only a few milliseconds.

Python Estimate pi from random points

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The estimate usually agrees with pi to two or three decimals. Run it again with a different seed and the third decimal changes: a Monte Carlo result is itself a random number. That is why you should always report an error estimate, not just the answer. For N points, the standard error of the pi estimate is 4*sqrt(p*(1-p)/N) with p = pi/4, which is about 1.64/sqrt(N).

Step 2: random walks

A random walker takes a step of +1 or -1 with equal probability. After T steps where does it stand? One walker is unpredictable, but thousands of them have a clear statistical pattern. Simulate all walkers at once with a matrix whose rows are walkers and whose columns are time steps:

MATLAB
W = 5000;                            % walkers
T = 400;                             % steps
steps = 2*(rand(W, T) > 0.5) - 1;    % +1 or -1
paths = cumsum(steps, 2);            % running sum along each row
final = paths(:, end);

mean(final)                          % near 0: no preferred direction
std(final)                           % near sqrt(T) = 20

The key function is cumsum(steps, 2), which accumulates along dimension 2 (across each row). The theory says the typical distance after T steps grows like sqrt(T), not like T: wandering is slow. You can check that by looking at the spread of positions at several times: std(paths(:, [25 100 400])) should be close to 5, 10 and 20.

Python Five thousand walkers at once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The histogram has a bell shape. The central limit theorem explains it: the final position is a sum of many independent steps, and sums of many independent quantities look normally distributed.

Step 3: an option-style payoff

A call option pays max(S - K, 0) at a future time: the holder may buy at the strike price K, so the payoff is the amount by which the final price S exceeds K, and zero otherwise. Its fair price is the average discounted payoff, where the average is taken over possible price paths. Monte Carlo is the standard tool when the payoff rules are complicated.

A simple model for the price is geometric Brownian motion: after time T the price is S0 * exp((r - sigma^2/2)*T + sigma*sqrt(T)*Z) with Z a standard normal random number. Take S0 = 100, strike K = 105, interest rate r = 0.03, volatility sigma = 0.2 and T = 1 year:

MATLAB
S0 = 100; K = 105; r = 0.03; sigma = 0.2; T = 1;
N  = 1e6;

Z = randn(N, 1);
ST = S0 * exp((r - sigma^2/2)*T + sigma*sqrt(T)*Z);
payoff = max(ST - K, 0);
price = exp(-r*T) * mean(payoff)

stderr = exp(-r*T) * std(payoff) / sqrt(N)    % error bar

The second result is as important as the first. The standard error std/sqrt(N) says how far the estimate is likely to be from the truth, and a rough 95 percent interval is price ยฑ 1.96*stderr. This model has an exact formula (Black-Scholes), which makes it a good test: a simulation that disagrees with the formula by many standard errors has a bug. This project is an exercise in numerical methods only and makes no statement about real markets or real prices.

Python Simulate the payoff and check against the formula

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The simulated price lands within about one or two standard errors of the exact value, as it should. In the stand-in run it was 7.149 against an exact 7.128, a difference of 1.65 standard errors. Notice that fewer than half of the paths pay anything (about 42 percent), and the average depends on the few large payoffs, which is why the error bar of such estimates is wider than you might expect.

Step 4: error against sample size

How many samples do you need? The error of a Monte Carlo average falls like 1/sqrt(N): to gain one more correct digit you need 100 times more samples. That is slow, and the slowness is the price of generality. The best way to see it is to repeat the pi estimate for growing N and plot the error on log-log axes, where a power law becomes a straight line with slope -1/2:

MATLAB
Ns = round(logspace(2, 6, 9));          % 100 ... 1,000,000
reps = 200;                             % repeat each size 200 times
err = zeros(size(Ns));
for k = 1:numel(Ns)
    est = 4 * mean(rand(Ns(k), reps).^2 + rand(Ns(k), reps).^2 < 1);   % reps estimates at once
    err(k) = sqrt(mean((est - pi).^2));                                 % RMS error
end
loglog(Ns, err, 'o-', Ns, 1.64./sqrt(Ns), '--')
legend('measured', '1.64/sqrt(N)')
xlabel('N'), ylabel('RMS error')

The loop is over the nine sample sizes only. For each size, a matrix with one column per repetition produces reps independent estimates in one go, and mean along dimension 1 averages each column.

Python Watch the error fall like 1/sqrt(N)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The measured points hug the dashed line, and the fitted slope comes out near -0.5. Note that the polyfit call is Polynomials and Curve Fitting used as a measuring tool.

Good practice

  • Seed for reproducibility. rng(7) at the top of a script lets you rerun and get the same numbers, which is essential for debugging. Different seeds are a quick way to see the natural variation.
  • Report the uncertainty. Always print the standard error next to the estimate.
  • Mind memory. rand(1e8, 1) needs 800 MB. For very large N, process in chunks of a million and combine the running sums.
  • Vectorize. The loop-free versions above run in milliseconds; a for loop over a million draws is far slower (see Performance and Memory).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the pi estimate, why multiply the fraction of points inside the circle by 4?

    Inside the unit square the quarter circle has area pi/4, so the fraction of hits estimates pi/4 and four times the fraction estimates pi.
  2. 2. What does cumsum(steps, 2) compute for a walkers-by-time matrix?

    The second argument is the dimension. Dimension 2 runs across each row, so each walker's steps are accumulated in time order.
  3. 3. A Monte Carlo estimate has a standard error of 0.01. About how many times more samples do you need to reduce it to 0.001?

    The error falls like 1/sqrt(N), so a tenfold smaller error needs a hundred times more samples.
  4. 4. Why report std(payoff)/sqrt(N) next to a Monte Carlo price?

    A simulation result is itself random. The standard error quantifies that randomness and gives a rough confidence interval.
  5. 5. On log-log axes, what does the Monte Carlo error against N look like?

    A power law error ~ N^(-1/2) becomes a straight line with slope -1/2 when both axes are logarithmic.

Summary

  • Monte Carlo estimates a quantity by averaging over many random samples; a logical vector's mean gives a probability.
  • Vectorize by drawing a whole matrix of random numbers: rows as repetitions, columns as time steps, then cumsum(..., 2) or mean along a dimension.
  • Random walkers spread like sqrt(T), and their final positions follow a bell curve.
  • A payoff estimate is the discounted mean of max(ST - K, 0); always add std/sqrt(N) as an error bar and test against a known formula when you can.
  • Error falls like 1/sqrt(N): slow but general. Seed with rng for reproducible runs.

Next, step back and compare the three languages in MATLAB, Octave and Python Compared.