# Open a graphic output
if (dev.cur() == 1) x11()
layout(c(1, 2))
par(mar=c(2.5,2,2,2))

# Vector of the average error given the sample size
error <- c()

# Make the sample size vary from 1 to 2500
for(l in seq(1, 2500, 1)) {
	# Just to let the user know that R is very slow....
	print(l)
	
	r <- 0
	N <- 1000
	
	# Generate N sets of L samples of a N(0, 1) random series
	for(i in 1:N) {
		x<-rnorm(l)
		
		# We know the true mean is zero. |mean(x)| is the error
		r <- r + abs(mean(x))
	}
	
	# Average error in %
	error <- c(error, 100 * r / N)
}

# Show the result
plot(error, type='h', col='darkgreen', main='Average % error given sample size in estimating the mean', ylim=c(0, 50))

# Draw lines for 20%, 10%, 5% and 1% error
abline(h=20, col='red')
abline(h=10, col='blue')
abline(h=5, col='orange')
abline(h=1, col='green')



# All the same for the variance
error <- c()
for(l in seq(1, 1000, 1)) {
    print(l)
    r <- 0
	N <- 10000
    for(i in 1:N) {
        x<-rnorm(l)
        
		# We know the true variance is one. |1 - var(x)| is the error
        r <- r + abs(1 - var(x))
    }
    
    error <- c(error, 100 * r / N)
}
# Second plot
plot(error, type='h', col='darkgreen', main='Average % error given sample size in estimating the variance', ylim=c(0, 50))
abline(h=20, col='red')
abline(h=10, col='blue')
abline(h=5, col='orange')
abline(h=1, col='green')

