import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as fm
# 实验参数设置
l = 0.8 # 针长
a = 1.0 # 平行线间距
# 定义样本空间: theta in [0, pi], x in [0, a/2]
theta_range = np.linspace(0, np.pi, 500)
x_boundary = (l / 2) * np.sin(theta_range) # 相交条件的临界曲线
# 创建图形
fig, ax = plt.subplots(figsize=(11, 6))
# 绘制样本空间的矩形边界
rect_x = [0, np.pi, np.pi, 0, 0]
rect_y = [0, 0, a/2, a/2, 0]
ax.plot(rect_x, rect_y, 'k-', linewidth=2.5, label='样本空间边界')
# 绘制相交条件的临界曲线
ax.plot(theta_range, x_boundary, 'r-', linewidth=3,
label=r'相交边界: $x = \frac{l}{2}\sin\theta$')
# 填充相交区域 (事件A)
ax.fill_between(theta_range, 0, x_boundary,
color='#E3120B', alpha=0.25,
label=r'事件$A$: 针与线相交')
# 坐标轴设置
ax.set_xlim(-0.1, np.pi + 0.1)
ax.set_ylim(-0.05, a/2 + 0.1)
ax.set_xticks([0, np.pi/4, np.pi/2, 3*np.pi/4, np.pi])
ax.set_xticklabels(['0', r'$\pi/4$', r'$\pi/2$', r'$3\pi/4$', r'$\pi$'], fontsize=14)
ax.set_yticks([0, a/4, a/2])
ax.set_yticklabels(['0', r'$a/4$', r'$a/2$'], fontsize=14)
ax.set_xlabel(r'针的夹角 $\theta$ (弧度)', fontsize=16, fontweight='bold')
ax.set_ylabel(r'针心到直线的距离 $x$', fontsize=16, fontweight='bold')
ax.set_title('Buffon投针问题的几何概率模型', fontsize=18, fontweight='bold', pad=20)
# 网格和图例
ax.grid(True, alpha=0.3, linestyle='--')
ax.legend(loc='upper right', fontsize=13, framealpha=0.95)
# 添加关键点标注
ax.annotate('最大投影点', xy=(np.pi/2, l/2), xytext=(np.pi/2 + 0.5, l/2 + 0.05),
arrowprops=dict(arrowstyle='->', color='#2C3E50', lw=2),
fontsize=12, color='#2C3E50', fontweight='bold')
plt.tight_layout()
plt.show()