python 如何求cdf,Python中计算CDF的方法

原创
admin 3小时前 阅读数 11 #Python

Python中可以使用SciPy库中的统计模块来计算累积分布函数(CDF),以下是一个简单的示例代码,演示如何使用Python计算CDF:

from scipy.stats import norm
import matplotlib.pyplot as plt
创建一个正态分布,均值为0,标准差为1
dist = norm(loc=0, scale=1)
生成一个均匀分布的随机变量,范围从-5到5
x = np.linspace(-5, 5, 400)
计算CDF
y = dist.cdf(x)
绘制CDF图
plt.figure(figsize=(8, 6))
plt.plot(x, y, label='CDF of normal distribution')
plt.xlabel('x')
plt.ylabel('CDF')
plt.title('Cumulative Distribution Function of Normal Distribution')
plt.legend()
plt.grid(True)
plt.savefig('CDF_normal_distribution.png')  # 保存图像
plt.show()

在上面的代码中,我们首先导入必要的库,即SciPy库中的统计模块和matplotlib库,我们创建一个正态分布,均值为0,标准差为1,我们生成一个均匀分布的随机变量,范围从-5到5,并使用正态分布对象的cdf方法计算每个随机变量的累积分布函数值,我们绘制CDF图并保存图像。

通过计算累积分布函数,我们可以了解概率分布的形状和特征,并在数据分析和统计推断中发挥重要作用。

热门