Archive for computer language

ultimate R recursion

Posted in Books, R, Statistics, University life with tags , , , , , , on January 31, 2012 by xi'an

One of my students wrote the following code for his R exam, trying to do accept-reject simulation (of a Rayleigh distribution) and constant approximation at the same time:

fAR1=function(n){
 u=runif(n)
 x=rexp(n)
 f=(C*(x)*exp(-2*x^2/3))
 g=dexp(n,1)
 test=(u<f/(3*g))
 y=x[test]
 p=length(y)/n #acceptance probability
 M=1/p
 C=M/3
 hist(y,20,freq=FALSE)
 return(x)
 }

which I find remarkable if alas doomed to fail! I wonder if there exists a (real as opposed to fantasy) computer language where you could introduce constants C and only define them later… (What’s rather sad is that I keep insisting on the fact that accept-reject does not need the constant C to operate. And that I found the same mistake in several of the students’ code. There is a further mistake in the above code when defining g. I also wonder where the 3 came from…)

cannonball approximation to pi

Posted in Statistics with tags , , , , , on October 8, 2011 by xi'an

This year, my daughter started writing algorithms in her math class (she is in seconde, which could correspond to the 10th grade). The one she had to write down last weekend was Buffon’s neddle and the approximation of π by Monte Carlo (throwing cannon balls was not mentioned!). Here is the short R code I later wrote to show her the outcome (as the class has not yet learned a computer language):

n=10^6
counter=0
#uniforms over the unit square
ray=runif(n)^2+runif(n)^2
#proportion within the quarter circle
conv=cumsum((ray<1))/(1:n)
plot(conv,type="l",col="steelblue",ylim=c(pi/4-2/sqrt(n),
     pi/4+2/sqrt(n)),xlab="n",ylab="proportion")
abline(h=pi/4,col="gold3")

and here is an outcome of the convergence of the approximation to π/4:

Follow

Get every new post delivered to your Inbox.

Join 557 other followers