R Code 4: Integration + My first chain

1. Simulation is great.
1a. What is the variance of a uniform distribution?
Why not draw a whole bunch of samples and compute sample variance?
var(runif(10000))

1b. Let X1 and X2 be distributed as uniform(0,1). What does X1-X2 look like? What is the 25th percentile?
X1=runif(10000)
X2=runif(10000)
Y=X1-X2
hist(Y)
quantile(Y,p=.25)

#########################################
#Integration by Sampling

What is the area of a circle with radius 1?
my.col=c("red","blue")
M=100
x=runif(M,-1,1)
y=runif(M,-1,1)
#box is area 4.
distance.from.zero=sqrt(x*x+y*y)
in.circle=(distance.from.zero<1)
par(pty='s')
plot(x,y,pch=19,col=my.col[as.integer(in.circle)+1])
area=4*sum(in.circle)/M
#compare to pi*r^2