Random Numbers & Simulation
Random numbers let you simulate things that are uncertain: queues, games of chance, noisy measurements, particles bouncing around, the spread of a disease. Running a model many times with random inputs and looking at the distribution of results is called Monte Carlo simulation. This lesson covers MATLAB's random-number functions, how to make results reproducible, how to turn uniform numbers into other distributions, and how to judge the accuracy of a simulation.
Note: MATLAB and Octave use different generators, so the same seed gives different numbers in the two programs. That's why the examples print only facts that don't depend on the particular numbers: sizes, ranges, and whether an estimate lands within a tolerance of the true value. The last section builds a small generator of our own that produces identical numbers everywhere.
The basic generators
| Function | Returns |
|---|---|
rand(m, n) |
Uniform numbers in the open interval (0, 1) |
randn(m, n) |
Standard normal numbers (mean 0, standard deviation 1) |
randi(imax, m, n) |
Integers from 1 to imax |
randi([a b], m, n) |
Integers from a to b |
randperm(n) |
A random ordering of 1:n |
randperm(n, k) |
k distinct integers from 1:n |
Size arguments work as for zeros: rand(3) is 3×3, rand(1, 5) a row, rand(size(A)) matches A.
u = rand(2, 4);
fprintf('rand(2, 4) has size %dx%d, all in (0,1): %d\n', size(u), all(u(:) > 0 & u(:) < 1));
d = randi([3 8], 1, 10000);
fprintf('randi([3 8]): min %d, max %d, distinct values %d, all whole: %d\n', ...
min(d), max(d), numel(unique(d)), all(d == round(d)));
p = randperm(10);
fprintf('randperm(10) is a permutation of 1:10: %d\n', isequal(sort(p), 1:10));
pick = randperm(49, 6);
fprintf('lottery draw: %d distinct numbers between 1 and 49: %d\n', numel(unique(pick)), all(pick >= 1 & pick <= 49));
z = randn(1, 1e5);
fprintf('randn: mean within 0.02 of 0: %d, std within 0.02 of 1: %d\n', abs(mean(z)) < 0.02, abs(std(z) - 1) < 0.02);rand(2, 4) has size 2x4, all in (0,1): 1
randi([3 8]): min 3, max 8, distinct values 6, all whole: 1
randperm(10) is a permutation of 1:10: 1
lottery draw: 6 distinct numbers between 1 and 49: 1
randn: mean within 0.02 of 0: 1, std within 0.02 of 1: 1
randperm is the tool for shuffling: deck(randperm(numel(deck))) reorders any array, and randperm(n, k) samples without replacement.
Reproducibility with rng
The numbers come from a deterministic algorithm (by default the Mersenne Twister) started from a seed. Setting the seed with rng makes a script produce the same random numbers every time it runs, which is essential for debugging and for results others can check:
| Call | Effect |
|---|---|
rng(42) |
Seed the generator with 42 |
rng('default') |
Back to the state MATLAB starts with |
rng('shuffle') |
Seed from the clock: different numbers each session |
s = rng; ... rng(s) |
Save the generator state and later restore it |
rng(42, 'twister') |
Seed and choose the algorithm explicitly |
rng(42);
a = rand(1, 5);
rng(42);
b = rand(1, 5);
fprintf('same seed, same numbers: %d\n', isequal(a, b));
s = rng; % remember the current state
x = randn(1, 3);
rng(s); % rewind
y = randn(1, 3);
fprintf('restored state repeats the draw: %d\n', isequal(x, y));
rng(43);
c = rand(1, 5);
fprintf('a different seed gives different numbers: %d\n', ~isequal(a, c));same seed, same numbers: 1
restored state repeats the draw: 1
a different seed gives different numbers: 1
Older code uses rand('seed', 42) or rand('state', 42); these switch MATLAB to legacy generators and are discouraged. Use rng.
Other distributions from uniform numbers
Many distributions can be generated with a line of arithmetic:
| Distribution | Recipe |
|---|---|
| Uniform on (a, b) | a + (b - a) * rand(n, 1) |
| Normal, mean μ, std σ | mu + sigma * randn(n, 1) |
| Bernoulli (success with probability p) | rand(n, 1) < p |
| Exponential with rate λ | -log(rand(n, 1)) / lambda (inverse-CDF method) |
| Discrete with probabilities w | sum(rand > cumsum(w)) + 1, or interp1 on the cumulative sum |
The inverse-CDF method works for any distribution whose cumulative distribution function F you can invert: if U is uniform, F⁻¹(U) has distribution F. MATLAB's Statistics and Machine Learning Toolbox (and Octave's statistics package) add random, exprnd, poissrnd, binornd and friends.
rng(1);
n = 1e5;
w = 2 + 3 * rand(n, 1); % uniform on (2, 5)
fprintf('uniform: range inside (2,5): %d, mean near 3.5: %d\n', all(w > 2 & w < 5), abs(mean(w) - 3.5) < 0.02);
h = 170 + 8 * randn(n, 1); % heights, mean 170, std 8
fprintf('normal: share within one std: %.2f (theory 0.68)\n', round(mean(abs(h - 170) < 8) * 50) / 50);
e = -log(rand(n, 1)) / 0.5; % exponential, rate 0.5 => mean 2
fprintf('exponential: all positive %d, mean near 2: %d\n', all(e > 0), abs(mean(e) - 2) < 0.05);
coin = rand(n, 1) < 0.3; % biased coin
fprintf('Bernoulli: logical %d, share near 0.3: %d\n', islogical(coin), abs(mean(coin) - 0.3) < 0.01);uniform: range inside (2,5): 1, mean near 3.5: 1
normal: share within one std: 0.68 (theory 0.68)
exponential: all positive 1, mean near 2: 1
Bernoulli: logical 1, share near 0.3: 1
The share within one standard deviation is rounded to the nearest 0.02, so the printed value is the same whatever numbers the generator produced.
Monte Carlo: estimating π
Throw random points into the unit square; the fraction that lands inside the quarter circle x² + y² ≤ 1 approaches π/4. Fully vectorised, a million points take a fraction of a second:
rng(2024);
N = 1e6;
x = rand(N, 1);
y = rand(N, 1);
inside = x.^2 + y.^2 <= 1;
piHat = 4 * mean(inside);
se = 4 * sqrt((pi/4) * (1 - pi/4) / N); % standard error of the estimate
fprintf('standard error with N = %d: %.4f\n', N, se);
fprintf('estimate within 4 standard errors of pi: %d\n', abs(piHat - pi) < 4 * se);standard error with N = 1000000: 0.0016
estimate within 4 standard errors of pi: 1
The key fact of Monte Carlo is in the standard error formula: it shrinks like 1/√N. Each extra decimal digit of accuracy costs 100 times more samples. That's slow for low-dimensional integrals (where integral is far better) but the rate doesn't depend on the dimension, which makes Monte Carlo the method of choice for high-dimensional problems.
Simulating a probability: the birthday problem
How likely is it that at least two of 23 people share a birthday? The exact answer is 1 − (365·364·…·343)/365²³. A simulation draws the birthdays with randi and checks for duplicates with unique:
rng(7);
people = 23;
trials = 20000;
hits = 0;
for k = 1:trials
days = randi(365, 1, people);
hits = hits + (numel(unique(days)) < people);
end
pSim = hits / trials;
pExact = 1 - prod((365 - (0:people-1)) / 365);
fprintf('exact probability: %.4f\n', pExact);
se = sqrt(pExact * (1 - pExact) / trials);
fprintf('simulation within 4 standard errors (%.4f): %d\n', 4 * se, abs(pSim - pExact) < 4 * se);exact probability: 0.5073
simulation within 4 standard errors (0.0141): 1
Surprisingly, just over 50%. Simulations like this are the easiest way to check an analytical answer, or to get one when the maths is too hard.
A random walk
A walker steps +1 or −1 with equal probability. After n steps the expected position is 0 and the variance is n. cumsum turns a matrix of steps into whole paths, one walk per column:
rng(11);
n = 400; walkers = 5000;
steps = 2 * (rand(n, walkers) < 0.5) - 1; % +1 or -1
paths = cumsum(steps); % n x walkers
final = paths(end, :);
fprintf('paths matrix: %dx%d, final positions even: %d\n', size(paths), all(mod(final, 2) == 0));
fprintf('mean final position within 1.5 of 0: %d\n', abs(mean(final)) < 1.5);
fprintf('variance within 10%% of n = %d: %d\n', n, abs(var(final) / n - 1) < 0.1);paths matrix: 400x5000, final positions even: 1
mean final position within 1.5 of 0: 1
variance within 10% of n = 400: 1
A generator of your own: identical numbers everywhere
When results must be bit-for-bit identical across MATLAB, Octave, Python and C (for tests, teaching or a shared benchmark), implement a simple generator yourself. The Park–Miller "minimal standard" linear congruential generator computes x ← 16807·x mod (2³¹ − 1). Its products stay below 2⁵³, so double arithmetic is exact, and its published check value lets you verify the implementation: starting from seed 1, the 10 000th value must be 1043618065.
x = 1;
for k = 1:10000
x = mod(16807 * x, 2^31 - 1);
end
fprintf('10000th value from seed 1: %d (expected 1043618065)\n', x);
u = lcg(5, 1);
fprintf('first five uniforms: %s\n', sprintf('%.6f ', u));
rolls = floor(6 * lcg(6000, 2024)) + 1; % dice from the same generator
counts = accumarray(rolls', 1)';
fprintf('dice counts: %s (total %d)\n', mat2str(counts), sum(counts));
function u = lcg(n, seed)
% Park-Miller minimal standard generator: n uniforms in (0, 1)
a = 16807; m = 2^31 - 1;
x = seed;
u = zeros(1, n);
for k = 1:n
x = mod(a * x, m);
u(k) = x / m;
end
end10000th value from seed 1: 1043618065 (expected 1043618065)
first five uniforms: 0.000008 0.131538 0.755605 0.458650 0.532767
dice counts: [972 1032 1004 963 1010 1019] (total 6000)
These numbers are the same in every program that implements the formula, which is why they can be printed here. Don't use such a simple generator for serious statistics: its period (about 2·10⁹) and quality are far below the Mersenne Twister's. accumarray(rolls', 1) counts how often each value occurs.
Learn more: distributions and the theory behind sampling are in Probability Distributions and the Central Limit Theorem; NumPy's generators are in NumPy Random.
Test yourself
Which call returns 5 distinct integers between 1 and 20?
randi(20, 1, 5)randperm(20, 5)rand(5) * 20randn(1, 5)
A Monte Carlo estimate with N = 10 000 samples has a standard error of 0.01. About how many samples give 0.001?
- 100 000
- 1 000 000
- 20 000
- 10 000 000 000
You run the same script with rng(5) in MATLAB and in Octave. What do you get?
- Identical random numbers
- Different numbers, but each program repeats its own sequence on every run
- An error in Octave
- Random numbers that change each run