More on Simulation stat 480
 Heike Hofmann

advertisement
More on Simulation
stat 480
Heike Hofmann
Outline
• Investigating distributions
• Monte Carlo integration
Generating random
numbers in R
•
runif (uniform), rpois (poisson), rnorm
(normal), rbinom (binomial), rgamma
(gamma), rbeta (beta)
• First argument for all is n, number of
samples to generate
parameters of the distribution • Then
(always check that the distribution is parameterized
the way you expect)
Aims of Simulations
• Learn how to simulate data to:
• Test your statistical intuition
• Perform power calculation
• Experiment with a new technique on
known data
• Learn how to use functions to reduce
duplication
Basics of simulation
• Want to:
• generate random numbers from known
distribution
• want to repeat the simulation multiple
times
Your turn
• Big Goal:
Investigate: how does a Beta density function look
like for different shape parameters?
• For that:
have a look at the density in help(rbeta).
Which parameters will be crucial?
• simulate n=1000 random numbers from a Beta
distribution with different parameters, and plot
histograms
Repetitions
• Use the replicate function
• replicate(n, expression)
•replicate(10, mean(rnorm(100)))!
•qplot(replicate(100,
mean(rnorm(10))), type="histogram")
Your turn
• Plot histogram of:
• 1000 x mean of 10 Unif(0, 10)
• 1000 x mean of 100 Unif(0, 10)
• 100 x mean of 1000 Unif(0, 10)
• What do the last three examples show?
Experiment with the number of samples
Re-Sampling
•
•
sample() allows to “scramble” the data
sample(length(x), length(x),
replace=F)
reorders the indices of vector x.
This is called a permutation.
!
• this might be a helpful function for the
homework ….
Monte Carlo Simulation
• often times used for numerical integration
• idea: (1) find an envelope (usually
a rectangle) for the area
of a function you want to
integrate
(2) ‘shoot’ uniform points into the rectangle,
(3) Compute the ratio of points below the graph
and the overall number of points. This is an
estimate for the integral.
Rest of the class:
• We want to numerically find the value of π
• We know: a circle with a radius of 1, has an
area of π
• We can put an envelope around that are,
i.e. surround the circle with a square
• We use Monte Carlo integration to
compute π
Your turn
Monte Carlo Integration: What is the area of a circle of radius r=1 ?
• Generate two vectors x and y as samples from
random uniform U[-1,1]
• Calculate vector hit that is true, if x^2+y^2 < 1
• Compute the ratio of number of hits
compared to number of tries
• Calculate the area from the previous ratio what is the size of the circle?
Download