### Archive

Posts Tagged ‘metropolis’

## A von Mises variate…

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 $f(x):=\frac{e^{b \text{Cos}[y-a]}}{2 \pi \text{BesselI}[0,b]}$, for $-\pi \leq x\leq \pi$.

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)