到了二元随机变量的部分,概率论就变得抽象了起来,只剩下了各种难以琢磨的理论公式。还好,我们还有一个有趣的例子,可以通过模拟来验证理论分析的结果。
1. 题目
设有一件工作需要甲乙两人接力完成,完成时间不能超过30分钟,设甲先干了X分钟,再由乙完成,加起来总共用了Y分钟。
若𝑋~𝑈(0, 30),在X=x的条件下,𝑌~𝑈(𝑥, 30)。若两人总共花了25分钟完成工作时,求甲工作时间不超过10分钟的概率。
2. 分析
根据课堂上的分析,我们知道甲工作时间不超过10分钟的概率:
3. Python 模拟思路
那么我们怎么使用Python对这一过程进行模拟呢?在python的numpy库中,我们可以生成均匀分布的函数numpy.random.uniform(low, high, num),其中low与high是生成的随机数的区间,num是生成的随机数的个数。
因此,甲工作时间X~U(0, 30), 即甲工作时间,而总时间
, 那么乙工作的
时间即为总时间T减去甲工作的时间t:
而在我们需要求解的条件概率中,我们知道,对于连续型随机变量,,即随机变量取得的为一定值的概率=0,因此我们可以认为的定一个小区间,即
, 然后统计其中
的概率。
4. Python 程序
# the 1 st worker spent X min, then the other worker spent n min
# X~U(0,30), the total time Y ~U(X, 30)
# What is the distribution of Y?
import math
import numpy as np
from matplotlib import pyplot as plt
num = 100000
# x = np.arange(num)
# y = np.random.uniform(0, 30, num)
sigma = 0.1
x = np.arange(num)
first_time = np.zeros(num)
count = 0
flag = 0
second_time = np.zeros(num)
for i in range(num):
first_time[i] = np.random.uniform(0, 30)
total_time = np.random.uniform(first_time[i], 30)
second_time[i] = total_time - first_time[i]
if abs(total_time - 25) <= 0.2:
count += 1
if first_time[i] <= 10:
flag += 1
plt.style.use('seaborn')
f = plt.figure(1)
plt.scatter(x, first_time, alpha = 0.5, color = 'g')
print(count, flag, flag/count*1.0)
plt.title("The time first worker spent")
g = plt.figure(2)
plt.scatter(x, second_time, alpha = 0.5, color = 'r')
plt.title("The time second worker spent")
#plt.show()
最后,模拟了100000次,得到的结果大概是0.2257,与理论值也算比较接近了。我觉得也算是圆满解决了这个问题。