🛠️ToolsShed

样本量计算器

计算调查和研究所需的样本量。

常见问题

代码实现

import math

# Z-values for common confidence levels
Z_VALUES = {80: 1.282, 85: 1.440, 90: 1.645, 95: 1.960, 99: 2.576}

def sample_size(confidence: int, margin_of_error: float, population: int = None) -> int:
    """
    Calculate required sample size.
    confidence: confidence level (80, 85, 90, 95, or 99)
    margin_of_error: as a decimal (e.g. 0.05 for 5%)
    population: total population size (None for infinite)
    """
    z = Z_VALUES[confidence]
    p = 0.5  # worst-case proportion
    n = (z ** 2 * p * (1 - p)) / (margin_of_error ** 2)

    if population is not None and population > 0:
        n = n / (1 + (n - 1) / population)

    return math.ceil(n)

# Examples
print(sample_size(95, 0.05))           # 385 (infinite population)
print(sample_size(95, 0.05, 1000))     # 278 (adjusted for N=1000)
print(sample_size(99, 0.03))           # 1842
print(sample_size(90, 0.05))           # 271

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.