Title: Generating Random Numbers
1Generating Random Numbers
2Generating Random Numbers
Anyone who considers arithmetical methods of
producing random digits is, of course, in a state
of sin. -- John von Neumann, 1951
- Generating truly random numbers is generally both
impractical and in fact undesirable - What we can do is generate pseudorandom numbers
- They can be reproduced starting from the same
seed - They must have good statistical properties (see
RANDU for a remarkable failure)
3Uniform (0,1)
- Linear congruential method
4Methods
- Inverse Transform
- Acceptance-Rejection
- Convolution
- Composition
5Uniform
6Uniform
- function genuni(N,a,b)
- urand(1,N)
- xa(b-a).u
- minxmin(x)
- maxxmax(x)
- NumBins51
- hhist(x,NumBins)
- for k1NumBins,
- bincenters(k)minx((maxx-minx)/NumBins)(k-1/
2) - end
- hh/sum(h)
- bar(bincenters,h)
Or use Matlab function unifrnd(a,b,M,N)
7Exponential
8Exponential
function genexp(N,lambda) urand(1,N) x-1/lambda
.log(1-u)
Or use Matlab function exprnd(lambda,M,N)
9Normal
- Box-Muller Method
- Generate
- Generate
- Set
- Return
- Dont use it with adjacent numbers produced by a
linear congruential generator
10Normal
function gennormal(N,mu,sigma) for i1N
u1rand u2rand z1sqrt(-2log(u1))cos(
2piu2) z2sqrt(-2log(u1))sin(2piu2)
x1(i) mu sigmaz1 x2(i) mu
sigmaz2 end
Or use Matlab function normrnd(mu,sigma,M,N)
11Binomial
- Generate IID Bernoulli(p) random
numbers - Return
12Binomial
function genbino(N,n,p) for i1N,
urand(1,n) y(ultp) x(i)sum(y) end
Or use Matlab function binornd(n,p,M,N)
13Geometric
14Geometric
function gengeo(N,p) urand(1,N)
xceil(log(1-u)/log(1-p))
Or use Matlab function geornd(p,M,N)
15Poisson
- Set
- Generate and replace by
- If accept else increase
by one and return to step 2
16Poisson
function genpois(N,lambda) for i1N,
k0p1 urand ppu while
pgtexp(-lambda) urand ppu
kk1 end x(i)k end
Or use Matlab function poissrnd(lambda,M,N)
17Multivariate Normal
- Generate IID random variables
- Decompose into a lower and upper triangular
matrix - (Cholesky decomposition)
- Return
18Multivariate Normal
Or use Matlab function mvnrnd(mu,sigma,N)