Professional Documents
Culture Documents
Some applications:
I Simulation of complex systems
I MCMC (Markov Chain Monte Carlo) methods
I Encryption
I Bootstrap methods
I Design of experiments
I performance testing
I Simulation testing of models and estimation procedures
I Other areas where producing an unpredictable result is desirable
How do we get random numbers?
The Mersenne Twister uses a random seed as input: Constructed from time
and session ID.
I You can replace the random seed with a fixed seed with the set.seed() function.
8
I Calculate the integral
6
4
f
Z 2
f (x)dx
2
0
0
I A Monte Carlo method is: 0 1 2 3 4 5 6
x
1. Simulate uniformly distributed points (x1 , y1 ), . . . , (xN , yN )
in [0, 2] [0, 8].
2. Estimate the probability of points being below the curve f
via:
8
bu = #below
P
6
N
4
3. The area of the entire box is 16, so the estimated
f
integral, the area under the curve, becomes
2
Z 2
0
f (x)dx 16 P
bu 0 1 2 3 4 5 6
0
x
Practical Implementation
> x<-runif(1000000,0,2*pi)
> y<-runif(1000000,0,8)
> phat.under<-mean(y<exp(2*cos(x-pi)))
> phat.under*16*pi
[1] 14.29143
Histogram of p.sim
150
100
Frequency
50
0
p.sim
> x<-rnorm(1000)
> plot(density(x),xlim=c(-8,16))
density.default(x = x)
0.4
0.3
Density
0.2
0.1
0.0
5 0 5 10 15
y<-rnorm(1000,mean=8)
lines(density(y),col="blue")
density.default(x = x)
0.4
0.3
Density
0.2
0.1
0.0
5 0 5 10 15
lines(density(rnorm(1000,sd=2)),col="red")
lines(density(rnorm(1000,mean=8,sd=2)),col="green")
density.default(x = x)
0.4
0.3
Density
0.2
0.1
0.0
5 0 5 10 15
lines(density(rnorm(1000,sd=4)),col="purple")
lines(density(rnorm(1000,mean=8,sd=4)),col="cyan")
density.default(x = x)
0.4
0.3
Density
0.2
0.1
0.0
5 0 5 10 15
The numbers distribute themselves around 0 and 8, with even more increased
variation.
Simulation of complex systems: Example
How many time units does it take to collect the food in a day?
Ants collecting food: Initialization
9 objects to keep track of. We assign initial values, and write them to a text
file for later use:
> my.text<-"time.ants<-0
+ at.anthill<-rep(TRUE,3)
+ done.all<-0
+ done<-rep(0,3)
+ food<-c(rpois(8,lambda=10),0,0)
+ site<-c(10,10,10)
+ carry<-c(0,0,0)
+ visited.sites<-list(numeric(0),numeric(0),numeric(0))
+ total.visited.sites<-rep(0,3)"
> writeLines(my.text,con="Data/initialize.txt")
Ants collecting food: Loop
We simulate the the system by sourcing the initialization and and loop code:
> total.time<-numeric(100)
> for(k in 1:100){
+ source("Data/initialize.txt")
+ source("Data/loop.txt")
+ total.time[k]<-time.ants
+ }
Histogram of total.time
40
Frequency
20
0
total.time
Further reading on distributions
The mathematical exposition is modest, and while examples are from the
medical world, the methods apply universally.
You can also check out your own field of expertise, for a statistics textbook
with relevant examples.