到了二元隨機變量的部分,概率論就變得抽象了起來钙态,只剩下了各種難以琢磨的理論公式册倒。還好,我們還有一個有趣的例子驻子,可以通過模擬來驗證理論分析的結果。
1. 題目
設有一件工作需要甲乙兩人接力完成缤剧,完成時間不能超過30分鐘域慷,設甲先干了X分鐘,再由乙完成兄纺,加起來總共用了Y分鐘化漆。
若??~??(0, 30)钦奋,在X=x的條件下疙赠,??~??(??, 30)朦拖。若兩人總共花了25分鐘完成工作時,求甲工作時間不超過10分鐘的概率捍岳。
2. 分析
根據課堂上的分析睬隶,我們知道甲工作時間不超過10分鐘的概率:
3. Python 模擬思路
那么我們怎么使用Python對這一過程進行模擬呢?在python的numpy庫中银萍,我們可以生成均勻分布的函數(shù)numpy.random.uniform(low, high, num)恤左,其中l(wèi)ow與high是生成的隨機數(shù)的區(qū)間,num是生成的隨機數(shù)的個數(shù)戳气。
因此巧鸭,甲工作時間X~U(0, 30), 即甲工作時間,而總時間, 那么乙工作的時間即為總時間T減去甲工作的時間t:
而在我們需要求解的條件概率中览闰,我們知道巷折,對于連續(xù)型隨機變量,油吭,即隨機變量取得的為一定值的概率=0署拟,因此我們可以認為的定一個小區(qū)間,即, 然后統(tǒng)計其中的概率心包。
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娃殖,與理論值也算比較接近了。我覺得也算是圓滿解決了這個問題堕虹。