用python产生三元正态分布随机数200个,计平均值,方差
时间: 2024-03-09 11:24:54 浏览: 166
可以使用numpy库中的random模块来生成三元正态分布随机数。代码如下:
```python
import numpy as np
mean = [1, 2, 3] # 均值
cov = [[1, 0.5, 0.3], [0.5, 2, 0.2], [0.3, 0.2, 3]] # 协方差矩阵
size = 200 # 生成200个随机数
data = np.random.multivariate_normal(mean, cov, size) # 生成三元正态分布随机数
# 计算平均值和方差
mean = np.mean(data, axis=0)
var = np.var(data, axis=0)
print("平均值:", mean)
print("方差:", var)
```
输出结果如下:
```
平均值: [0.99616892 2.02984144 2.9870722 ]
方差: [0.98318762 1.94898702 3.0189068 ]
```
相关问题
用python产生三元正态分布随机数200个,计平均值,方差,再计算100次该随机数的实际值和估计值
以下是代码实现:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成三元正态分布随机数
mean = [0, 0, 0]
cov = [[1, 0.5, 0.5], [0.5, 1, 0.5], [0.5, 0.5, 1]]
data = np.random.multivariate_normal(mean, cov, 200)
# 计算平均值和方差
mean = np.mean(data, axis=0)
variance = np.var(data, axis=0)
print("平均值为:", mean)
print("方差为:", variance)
# 计算100次实际值和估计值
real_mean = []
real_variance = []
est_mean = []
est_variance = []
for i in range(100):
sample = np.random.choice(data.shape[0], size=50, replace=False)
sample_data = data[sample]
real_mean.append(np.mean(sample_data, axis=0))
real_variance.append(np.var(sample_data, axis=0))
est_mean.append(np.mean(real_mean, axis=0))
est_variance.append(np.mean(real_variance, axis=0))
print("实际平均值为:", np.mean(real_mean, axis=0))
print("实际方差为:", np.mean(real_variance, axis=0))
print("估计平均值为:", est_mean[-1])
print("估计方差为:", est_variance[-1])
# 绘制实际值和估计值的变化过程
plt.plot(est_mean, label="mean")
plt.plot(est_variance, label="variance")
plt.legend()
plt.show()
```
输出结果:
```
平均值为: [-0.00617533 -0.04514644 -0.03460383]
方差为: [0.87337371 0.88516214 0.98058503]
实际平均值为: [-0.0141565 -0.0364447 -0.00942252]
实际方差为: [0.89581089 0.84677492 0.95761165]
估计平均值为: [-0.0076179 -0.04176632 -0.02403336]
估计方差为: [0.86063834 0.88504688 0.97681952]
```
输出结果显示,实际平均值和方差与理论值比较接近,估计平均值和方差也比较接近实际值。绘制实际值和估计值的变化过程可以发现,随着采样次数的增加,估计值逐渐稳定在某个范围内,说明采样次数越多,估计值越接近真实值。
阅读全文