Skip to content

Instantly share code, notes, and snippets.

@emgullufsen
Created June 10, 2016 21:50
Show Gist options
  • Save emgullufsen/b98a98c49b185f81f10e27750e2a6b4e to your computer and use it in GitHub Desktop.
Save emgullufsen/b98a98c49b185f81f10e27750e2a6b4e to your computer and use it in GitHub Desktop.
# Eric Gullufsen
# Visualize the central limit theorem
# take 10, 50, 100, 1000 random samples of size ten of integers in [0, 10]
# take average of each one
# plot these
# the resulting probability density function will look incresingly 'normal'
# as n increases - the number of samples taken
SAMPLE_SPACE <- 0:10
SAMP_SIZE <- 10
ns <- c(10, 50, 100, 1000, 2000)
for (n in ns)
{
counts <- vector(mode="numeric", length = n)
# regions of the possible values the mean can take on
regs <- seq(0, 10, length.out = (n + 1))
# make vector of midpoints of the region for plotting
regs_mid <- c()
for (c in 1:n)
{
regs_mid <- c(regs_mid, ((regs[c] + regs[(c + 1)]) / 2))
}
# simulate the runs, using runif and floor to generate the random integers
for (i in 1:n)
{
# generate randoms
samp <- floor(runif(10, 0, 11))
meme <- mean(samp)
# counting the number of runs giving a mean value within each of the regions
for (j in 1:n)
{
if ((meme >= regs[j]) && (meme < regs[(j + 1)]))
counts[j] <- counts[j] + 1
}
}
probs <- counts / n
plot(regs_mid, probs, type="h", xlab="Expected Value", ylab="Probability")
legend(x="topleft", legend=c(paste("n = ", toString(n))), bty="n")
# plot(regs_mid, probs, type="p")
# legend(x="topleft", legend=c(paste("n = ", toString(n))), bty="n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment