"""第 4 章：合成观测的均值区间与重复抽样；只使用标准库。"""

from math import sqrt
from random import Random
from statistics import mean, stdev


OBSERVATIONS = [56, 58, 59, 61, 62, 64]
ERROR_A = [4, 5, 3, 6, 4, 5]
ERROR_B = [3, 4, 2, 5, 5, 3]
T_975_DF5 = 2.570581835636314  # t 分布，自由度 5，97.5% 分位点


def mean_interval_six(values):
    if len(values) != 6:
        raise ValueError("本例的临界值只适用于 6 个独立观测")
    center = mean(values)
    standard_error = stdev(values) / sqrt(6)
    radius = T_975_DF5 * standard_error
    return center, standard_error, center - radius, center + radius


def repeated_samples(size, repeats=1000, seed=2026):
    rng = Random(seed)
    # 人为设定总体为 N(60, 6²)，真实项目通常不知道总体参数。
    return [[rng.gauss(60, 6) for _ in range(size)] for _ in range(repeats)]


def main():
    center, se, low, high = mean_interval_six(OBSERVATIONS)
    print(f"样本均值：{center:.2f} 秒，样本标准差：{stdev(OBSERVATIONS):.2f} 秒")
    print(f"估计标准误：{se:.2f} 秒，95% 均值区间：[{low:.2f}, {high:.2f}]")
    difference = [b - a for a, b in zip(ERROR_A, ERROR_B)]
    center, se, low, high = mean_interval_six(difference)
    print(f"B−A 平均误差差：{center:.3f} 秒，区间：[{low:.3f}, {high:.3f}]")

    samples = repeated_samples(6)
    intervals = [mean_interval_six(row) for row in samples]
    coverage = sum(low <= 60 <= high for _, _, low, high in intervals) / len(intervals)
    print(f"1000 次模拟中，均值区间覆盖 60 秒的比例：{coverage:.1%}")
    for size in [6, 60]:
        averages = [mean(row) for row in repeated_samples(size)]
        print(f"每次抽 {size} 条，1000 个样本均值的标准差：{stdev(averages):.3f} 秒")


if __name__ == "__main__":
    main()
