Python中random.random相关概率密度函数(PDF)绘制问题排查
问题分析
你的代码主要存在三个核心错误:
- 样本量严重不足:每次调用
random.random()仅生成1个随机数,单一样本完全无法反映概率分布特征,统计PDF需要至少数千到数十万级的样本量。 - 绘图方法选择错误:
plt.plot()是用来绘制折线趋势图的,概率密度分布需要使用直方图函数plt.hist(),同时要开启density=True参数将计数结果归一化为概率密度。 - 缺少分布统计逻辑:绘制PDF需要将样本取值范围划分为多个区间统计频率,现有代码完全没有这一步骤。
修正后的可运行代码
import random import matplotlib.pyplot as plt # 统一生成10万个样本,样本量越大分布越贴合理论PDF sample_num = 100000 # 第一个图:单个random.random()的PDF plt.figure('PDF for random.random()', figsize=(8,4)) plt.title('PDF for random.random()') samples1 = [random.random() for _ in range(sample_num)] # 分50个箱绘制直方图,归一化为密度,加边缘色提升可读性 plt.hist(samples1, bins=50, density=True, edgecolor='black') plt.xlabel('取值') plt.ylabel('概率密度') # 第二个图:两个随机数相加的PDF plt.figure('PDF for random.random() + random.random()', figsize=(8,4)) plt.title('PDF for random.random() + random.random()') samples2 = [random.random() + random.random() for _ in range(sample_num)] plt.hist(samples2, bins=50, density=True, edgecolor='black') plt.xlabel('取值') plt.ylabel('概率密度') # 第三个图:三个随机数相加的PDF plt.figure('PDF for random.random() + random.random() + random.random()', figsize=(8,4)) plt.title('PDF for random.random() + random.random() + random.random()') samples3 = [random.random() + random.random() + random.random() for _ in range(sample_num)] plt.hist(samples3, bins=50, density=True, edgecolor='black') plt.xlabel('取值') plt.ylabel('概率密度') plt.show()
效果说明
运行后三个输出图分别对应:
- 单个随机数是[0,1]区间的均匀分布,概率密度基本为水平直线,符合理论值1
- 两个随机数相加为三角分布,取值范围[0,2],在取值1处密度最高
- 三个随机数相加呈现明显的钟形分布,符合中心极限定理,和你参考的示例图效果一致。
内容的提问来源于stack exchange,提问作者livemyaerodream
相关产品推荐
相关产品推荐

