Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Acceptance-rejection methods
This post is based on chapter 1.4 of Advanced Markov Chain Monte Carlo.
Another method of generating random variates from distributions is to use acceptance-rejection methods. Basically to generate a random number from
Repeat until we generate a value from step 2:
1. Generate
from and from 2. If
, return (as a random deviate from ).
Example: the standard normal distribution
This example illustrates how we generate
On setting
since both
R code
This example is straightforward to code:
myrnorm = function(M){ while(1){ u = runif(1); x = rlogis(1, scale = 0.648) if(u < dnorm(x)/M/dlogis(x, scale = 0.648)) return(x) } }
To check the results, we could call myrnorm
a few thousand times:
hist(replicate(10000, myrnorm(1.1)), freq=FALSE) lines(seq(-3, 3, 0.01), dnorm(seq(-3, 3, 0.01)), col=2)
Example: the standard normal distribution with a squeeze
Suppose the density
The modified algorithm is as follows:
Repeat until we generate a value from step 2:
1. Generate
from and from 2. If
or , return (as a random deviate from ).
Hence, when
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.