Created
October 16, 2013 17:22
-
-
Save fditraglia/7011503 to your computer and use it in GitHub Desktop.
This is the source code to accompany my example on the Bernoulli and Binomial RVs: http://www.ditraglia.com/econ103/Bernoulli_Binomial.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#This function simulates n independent, identically distributed Bernoulli Random Variables | |
rbern <- function(n, p){ | |
sims <- sample(0:1, size = n, replace = TRUE, prob = c(1-p, p)) | |
return(sims) | |
} | |
rbern(30, 0.1) | |
rbern(30, 0.5) | |
rbern(30, 0.9) | |
#This function simulates n independent, identically distributed Bernoulli Random Variables and returns their sum | |
rbern.sum <- function(n, p){ | |
sims <- rbern(n, p) | |
return(sum(sims)) | |
} | |
rbern.sum(50, 0.1) | |
rbern.sum(50, 0.5) | |
rbern.sum(50, 0.9) | |
binom.sims <- replicate(10^5, rbern.sum(10, 0.5)) | |
head(binom.sims) | |
p.sim <- table(binom.sims)/10^5 | |
p.sim | |
plot(p.sim, type = 'h') | |
support <- 0:10 | |
p.true <- dbinom(support, size = 10, prob = 0.5) | |
rbind(support, p.true) | |
plot(support, p.true, type = 'h') | |
p.sim - p.true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment