Sunday, February 1, 2015

R5. Cumulative Binomial Distribution in R

The pbinom function generates cumulative probabilities based on the Binomial Distribution.


A uniform distribution is tested over 1000 trials to get similar curve.


The number of successful outcomes in each trial is 0 (never) to 100 (always) with 50 maximum probability, since the success probability is 0.5.

# ex5.R
num_trials <- 1000
each_trial <- 100
p <- 0.5
x <- 0:each_trial
sig <- numeric(num_trials)
sig1 <- pbinom(x, size = each_trial, prob = p)
for (t in 1:num_trials) {
  tr <- runif(each_trial)
  sig[t] <- sum(tr<=p)
}
sigc <- numeric(length(x))
for (i in x){
  sigc[i+1] <- sum(sig==i)
}
plot(x, cumsum(sigc)/num_trials, type = 'l', col = 'red',
     xlab ='Success', ylab = 'Cumulative Probability',
     main = 'Cumulative Binomial Distribution')
lines(x, sig1, col = rgb(0, 1, 0, 0.5))

Output:

No comments:

Post a Comment