Here is a simple Python implementation (not requiring any external libraries):
# https://github.com/shawnohare/samplesize/blob/master/samplesize.py
def sampleSize(population_size, margin_error=.05,confidence_level=.95,sigma=1/2):
alpha = 1 - (confidence_level)
zdict = {
.90: 1.645,
.91: 1.695,
.99: 2.576,
.97: 2.17,
.94: 1.881,
.93: 1.812,
.95: 1.96,
.98: 2.326,
.96: 2.054,
.92: 1.751
}
if confidence_level in zdict:
z = zdict[confidence_level]
else:
from scipy.stats import norm
z = norm.ppf(1 - (alpha/2))
N = population_size
M = margin_error
numerator = z**2 * sigma**2 * (N / (N-1))
denom = M**2 + ((z**2 * sigma**2)/(N-1))
return int(numerator/denom + 0.5)
for population in [100,1000,10000,50000]:
n = sampleSize(population)
print("Population %d requires sample size of %d" % (population, n))
Result:
Population 100 requires sample size of 80
Population 1000 requires sample size of 278
Population 10000 requires sample size of 370
Population 50000 requires sample size of 381
Validated by checking: https://www.surveymonkey.com/mp/sample-size-calculator/