(This article was first published on Stats raving mad » R, and kindly contributed to R-bloggers)
Inspired from a mail that came along the previous random generation post the following question rised :
How to draw random variates from the Von Mises distribution?
First of all let’s check the pdf of the probability rule, it is
, for
.
Ok, I admit that Bessels functions can be a bit frightening, but there is a work around we can do. The solution is a Metropolis algorithm simulation. It is not necessary to know the normalizing constant, because it will cancel in the computation of the ratio. The following code is adapted from James Gentle’s notes on Mathematical Statistics .
n <- 1000
x <- rep(NA,n)
a <-1
c <-3
yi <-3
j <-0
i<-2
while (i < n) {
i<-i+1
yip1 <- yi + 2*a*runif(1)- 1
if (yip1 < pi & yip1 > - pi) {
if (exp(c*(cos(yip1)-cos(yi))) > runif(1)) yi <- yip1
else yi <- x[i-1]
x[i] <- yip1
}
}
hist(x,probability=TRUE,fg = gray(0.7), bty="7")
lines(density(x,na.rm=TRUE),col="red",lwd=2)
To leave a comment for the author, please follow the link and comment on his blog: Stats raving mad » R.
R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series,ecdf, trading) and more...


Zero Inflated Models and Generalized Linear Mixed Models with R.
Zuur, Saveliev, Ieno (2012).