概率示例
在本练习中,您将复习有放回与无放回抽样的区别。我们将用模拟来计算某事件的概率,并改变抽样方式,看看对概率有何影响。
设想一只装满彩色糖果的碗——3 颗蓝色、2 颗绿色、5 颗黄色。一次取出 1 颗,共取 3 颗,分别进行有放回和无放回抽样。您需要计算"3 颗糖果全为黄色"的概率。
本练习是课程的一部分
Python 中的统计模拟
练习说明
- 将
bowl设置为一个列表,其中包含 3 个蓝色'b'、2 个绿色'g'、5 个黄色'y'糖果。 - 分别进行有放回抽样得到 3 颗糖果(
sample_rep)以及无放回抽样得到 3 颗糖果(sample_no_rep)。 - 对于有放回样本,若
sample_rep中没有'b'或'g',则将success_rep加 1。类似地,若sample_no_rep中没有'b'或'g',则将success_no_rep加 1。 - 将成功次数分别除以迭代次数,得到相应的概率。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Set up the bowl
success_rep, success_no_rep, sims = 0, 0, 10000
bowl = list(____*3 + ____*2 + ____*5)
for i in range(sims):
# Sample with and without replacement & increment success counters
sample_rep = np.random.____(bowl, size=3, replace=____)
sample_no_rep = np.random.____(bowl, size=3, replace=____)
if ('b' not in sample_rep) & ('g' not in sample_rep) :
____
if ('b' not in sample_no_rep) & ('g' not in sample_no_rep) :
____
# Calculate probabilities
prob_with_replacement = ____/sims
prob_without_replacement = ____/sims
print("Probability with replacement = {}, without replacement = {}".format(prob_with_replacement, prob_without_replacement))