# Margin-of-error calculation in survey

I've been trying to replicate the results in this online calculator:

http://www.raosoft.com/samplesize.html

However, it seems that I am missing something. Exactly how do I solve the margin of error when all the other variables (sample size, confidence level, distribution and population*) are known?

I've tried to use the formulas on the page but I cannot arrive at the same result. Also using the formulas on bottom of http://www.resolutions.co.nz/sample_sizes.htm gives me somewhat different results. What am I missing?

*) = a small population so it cannot be assumed infinite.

It is possible to reproduce the page's Javascript formula, for example in R (with some minor adjustments, notably treating the confidence figure as two-tailed, but leaving it with the slightly confusing calculations using percentages).

MarginOfError <- function(sample,  confidence,  response,  population)           {
pcn <- qnorm( (100+confidence) / 200)
d1  <- pcn * pcn * response * (100-response)
d2  <- d1 * (population - sample) / (sample * (population-1) )
ifelse(d2>0 , sqrt(d2), 0)                                     }


For example

> MarginOfError(100, 95, 50, 20000)
 9.775534


corresponding to the 9.8% given on that page for a sample size of 100. The other Javascript formulae can similarly be reproduced.