跳到内容
🛠️ToolsShed

样本量计算器

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

关于此工具

样本量计算器会告诉你在结果可信之前需要调查多少受访者。它解决了研究中常见的问题:收集的回复太少会导致结果在统计上不可靠,太多则浪费时间和预算。

使用时,设置你期望的置信水平、可接受的误差范围、总体规模以及预期的回答分布,工具便会给出所需的样本量。它适用于市场调查、学术研究、A/B 测试规划和民意调查。

请记住,更高的置信水平或更小的误差范围总是需要更大的样本量。所有计算都在你的浏览器本地运行,因此输入的数据绝不会离开你的设备。

常见问题

代码实现

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.