Skip to content

Instantly share code, notes, and snippets.

@vladiim
Created October 22, 2017 21:47
Show Gist options
  • Select an option

  • Save vladiim/d874f5a0064cd13610a9c578765ac2ac to your computer and use it in GitHub Desktop.

Select an option

Save vladiim/d874f5a0064cd13610a9c578765ac2ac to your computer and use it in GitHub Desktop.
# Listing B.20 Exact binomial sample size calculation
errorProb <- function(targetRate,difference,size) {
pbinom(
ceiling(( targetRate - difference) * size),
size = size, prob = targetRate)
}
print(errorProb(0.045 , 0.004, est)) ## [1] 0.04153646
binSearchNonPositive <- function(fEventuallyNegative) {
low <- 1
high <- low + 1
while(fEventuallyNegative(high) > 0) {
high <- 2 * high
}
while(high > low + 1) {
m <- low + (high-low) %/% 2
if(fEventuallyNegative(m) > 0) {
low <- m
} else {
high <-m
}
}
high
}
actualSize <- function(targetRate, difference, errorProb) {
binSearchNonPositive(function(n) {
errorProb(targetRate, difference, n) - errorProb
})
}
size <- actualSize(0.045, 0.004, 0.05)
print(size) ## [1] 7623 print(errorProb(0.045,0.004,size)) ## [1] 0.04983659
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment