7.写出一个使用接受﹣拒绝法生成大小为 n、服从 Beta(a,b) 分布的随机样本的函数、生成一个大小为 1000、服从 Beta(3, 2) 分布的随机样本,画出样本的直方图并叠加绘制Beta(3,2) 密度曲线。
时间: 2024-10-15 13:23:00 浏览: 96
接受-拒绝法(Acceptance-Rejection Method)是一种基于概率密度函数生成随机数的技术。在Python中,我们可以使用numpy库以及matplotlib库来实现这个过程。首先,我们需要安装这两个库,如果还没安装的话:
```bash
pip install numpy matplotlib scipy
```
然后可以编写一个函数来生成Beta分布的随机样本,并画出直方图和密度曲线:
```python
import numpy as np
from scipy.stats import beta
import matplotlib.pyplot as plt
def generate_beta_samples(n, a, b):
# Beta distribution PDF
def beta_pdf(x, alpha, beta):
return x**(alpha - 1) * (1 - x)**(beta - 1)
# Generate uniform samples in [0, 1]
u = np.random.rand(n)
# Generate samples from the target distribution by acceptance-rejection method
v = np.random.beta(a, b, size=n)
accepted = u < beta_pdf(v, a, b) / beta.pdf(u.min(), a, b)
samples = v[accepted]
return samples
# Generate a sample of size 1000 with Beta(3, 2) distribution
n = 1000
a, b = 3, 2
sample = generate_beta_samples(n, a, b)
# Plot histogram and density curve
plt.hist(sample, bins=50, density=True, alpha=0.6, label='Sample')
x_values = np.linspace(0, 1, 1000)
pdf = beta.pdf(x_values, a, b)
plt.plot(x_values, pdf, 'r-', linewidth=2, label=f'Beta({a}, {b})')
plt.xlabel('Value')
plt.ylabel('Density')
plt.legend()
plt.show()
阅读全文