"""四分之一圆面积、样本预算与 Wilson 区间。""" import json # NumPy 表示点集和区间端点,Matplotlib 比较样本预算下的区间宽度。 import matplotlib.pyplot as plt import numpy as np def main(): budgets = np.array([25, 100, 500, 2000]) state = 13579 modulus = 2147483647 # 一行是一个点,两列依次为 x、y。一次生成最大预算,其他预算复用前缀。 points = np.empty((int(budgets[-1]), 2)) # 使用显式的小型生成器,便于另一门语言逐点复算。 for row in range(len(points)): for column in range(2): state = 16807 * state % modulus points[row, column] = state / modulus # 每行平方和小于等于 1 记一次命中。前 n 行的累计计数位于下标 n-1。 inside = np.square(points).sum(axis=1) <= 1 counts = np.cumsum(inside)[budgets - 1] ratio = counts / budgets # 命中率近似四分之一圆占单位正方形的面积,乘 4 转为 π 的估计。 estimates = 4 * ratio # Wilson 区间先用于命中率,再整体乘 4 得到 π 的区间。 z = 1.96 factor = 1 + z**2 / budgets center = (ratio + z**2 / (2 * budgets)) / factor half_width = z * np.sqrt(ratio * (1 - ratio) / budgets + z**2 / (4 * budgets**2)) / factor lower, upper = 4 * (center - half_width), 4 * (center + half_width) assert np.all(lower <= estimates) and np.all(estimates <= upper) # 左图颜色表达是否命中,右图误差棒为每个预算的区间,横轴用对数刻度。 # 各预算使用同一条随机序列的前缀,点估计之间会相关。 fig, axes = plt.subplots(1, 2, figsize=(8, 3.4), layout="constrained") axes[0].scatter(*points.T, c=np.where(inside, "tab:blue", "tab:orange"), s=4, alpha=.6) axes[0].set(xlabel="x", ylabel="y", aspect="equal") axes[1].errorbar(budgets, estimates, yerr=[estimates - lower, upper - estimates], fmt="o") axes[1].axhline(np.pi, linestyle="--", color="gray") axes[1].set(xlabel="Samples", ylabel="pi estimate", xscale="log") print("LAB_RESULT " + json.dumps({"counts": counts.tolist(), "estimates": estimates.tolist(), "lower": lower.tolist(), "upper": upper.tolist()})) plt.show() if __name__ == "__main__": main()