Skip to main content
 首页 » 编程设计

python之关于模拟中心极限定理的问题来自 Book Data Science from Scratch

2025年01月19日13TianFang

我正在阅读 Joel Grus 的《从零开始的数据科学》一书。我的问题特别针对第 6 章,作者在该章中使用二项式随机变量来模拟定理。

结果将是一个图表,其中包含二项式试验的概率分布和使用正态分布的近似图。这两个图应该非常相似。书中展示了这样一个图表: Author's Chart

他提供的代码是:

import random 
from matplotlib import pyplot as plt 
from collections import Counter 
 
def bernoulli_trial(p): 
    return 1 if random.random() < p else 0 
 
def binomial(n, p): 
    return sum(bernoulli_trial(p) for _ in range(n)) 
 
def make_hist(p, n, num_points): 
    data = [binomial(n, p) for _ in range(num_points)] 
    histogram = Counter(data) 
    plt.bar([x-0.4 for x in histogram.keys()], 
       [v / num_points for v in histogram.values()], 
       0.8, 
       color='0.75') 
 
    mu = p * n 
    sigma = math.sqrt(n * p * (1-p)) 
 
    # use a line chart to show the normal approximation 
    xs = range(min(data), max(data) + 1) 
    ys = [normal_cdf(i+0.5, mu, sigma) - normal_cdf(i-0.5, mu, sigma) for i in xs] 
    plt.plot(xs, ys) 
    plt.title('Binomial Distribution vs. Normal Approximation') 
    plt.show() 
 
make_hist(0.75, 100, 10000) 

我的问题是,在这一行中: [normal_cdf(i+0.5, mu, sigma) - normal_cdf(i-0.5, mu, sigma) for i in xs] 为什么作者使用+0.5 和-0.5?这有什么具体原因吗?

不知道有没有人遇到过这个问题。 提前致谢!

请您参考如下方法:

在 xs 变量中,您有一个包含步骤 1 的 X 坐标列表,例如[5,6,7,8,9,10]。在 ys 变量中,您需要获取相应的 Y 坐标和 normal_cdf(i+0.5, mu, sigma) - normal_cdf(i-0.5, mu, sigma) 在您的代码中是从i-0.5到i+0.5的积分,即宽度为(i+0.5) - (i-0.5) = 1,同步。

更容易理解的代码如下所示:

step = 1.0 
xs = range(min(data), max(data) + 1, step) 
ys = [normal_cdf(i + step / 2, mu, sigma) - normal_cdf(i - step / 2, mu, sigma) for i in xs]