函数正态分布
一、简介
正态分布是统计学中最为重要的分布之一,也称为高斯分布。正态分布在自然界中广泛存在,如人类身高、体重等,经常被用于描述和预测各种现象。本文将介绍如何用Python编写一个正态分布函数。
二、正态分布的概念
正态分布是指在数轴上以均值μ为对称轴呈钟形分布的连续随机变量的概率密度函数。其公式为:
![image.png](attachment:image.png)
其中x表示随机变量的取值,μ表示均值,σ表示标准差。
三、编写函数
1. 导入必要的库
我们需要导入numpy和matplotlib库来进行计算和绘图。
```python
import numpy as np
import matplotlib.pyplot as plt
```
2. 定义函数
我们可以定义一个名为normal_distribution的函数来实现正态分布。该函数接受三个参数:均值mu、标准差sigma和数据点数目num_points。
```python
def normal_distribution(mu, sigma, num_points):
    x = np.linspace(mu - 3 * sigma, mu + 3 * sigma, num_points)
    y = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(- (x - mu) ** 2 / (2 * sigma ** 2))
linspace numpy    return x, y
```
该函数首先使用numpy中的linspace函数生成一个包含num_points个数据点的一维数组x,该数组覆盖了以mu为中心,左右各3倍标准差sigma的区间。然后,我们使用正态分布的概率密度函数计算每个数据点的y值,并将它们存储在另一个一维数组y中。最后,我们返回x和y。
4. 绘制图形
我们可以使用matplotlib库来绘制正态分布曲线。
```python
mu, sigma = 0, 1
x, y = normal_distribution(mu, sigma, 1000)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('Probability density')
plt.title('Normal distribution')
plt.show()
```
在这里,我们首先定义了均值mu和标准差sigma。然后,我们调用normal_distribution函数来生成一组数据点x和y,并使用plot函数来绘制曲线。最后,我们添加了标签和标题,并使用show函数显示图形。
五、完整代码
```python
import numpy as np
import matplotlib.pyplot as plt
def normal_distribution(mu, sigma, num_points):
    x = np.linspace(mu - 3 * sigma, mu + 3 * sigma, num_points)
    y = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(- (x - mu) ** 2 / (2 * sigma ** 2))
    return x, y
mu, sigma = 0, 1
x, y = normal_distribution(mu, sigma, 1000)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('Probability density')
plt.title('Normal distribution')
plt.show()
```
六、结论
通过上述代码,我们可以轻松地生成正态分布曲线,并对其进行可视化。正态分布是一个非常重要的概率分布,广泛应用于各种领域。在实际应用中,我们可以根据需要调整均值和标准差来适应不同的数据集。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。