yun@dicom

导航

如何用 Python 来模拟概率

 

小朋友问我一个问题, 如何用 Python 来模拟概率. 

题目是: 从 [-2, -1, 0, 1, 2, 3] 中随机选择两个不同的数, 乘积为 0 的概率是多少?

我搜索并思考了一下, 得出以下几种方式:

choice_1 的思路是, 对列表进行深拷贝来模拟

choice_2 的思路是, 如果选到相同的数, 就放弃本次选择.

choice_3 直接用 random.sample () 函数, 味道最像 Python.

 

乘积为 0 用 (A1 == 0 or A2 == 0) 来判断, 性能方面可能快一点

 

 1 import random
 2 import copy
 3 
 4 lst = [-2, -1, 0, 1, 2, 3]
 5 
 6 def choice_1 (trials):
 7 
 8     total = 0
 9     found = 0.0
10 
11     while total < trials:
12         A1 = random.choice (lst)
13         lstbk = copy.deepcopy (lst)
14         lstbk.remove (A1)
15         A2 = random.choice (lstbk)
16         if (A1 == 0 or A2 == 0):
17             found += 1.0
18         total += 1
19 
20     print (found/total)
21 
22 
23 def choice_2 (trials):
24 
25     total = 0
26     found = 0.0
27 
28     while total < trials:
29         A1 = random.choice (lst)
30         A2 = random.choice (lst)
31         if (A1 == A2):
32             continue
33         if (A1 == 0 or A2 == 0):
34             found += 1.0
35         total += 1
36 
37     print (found/total)
38 
39 def choice_3 (trials):
40 
41     total = 0
42     found = 0.0
43 
44     while total < trials:
45         R = random.sample (lst, 2)
46         if (R[0] == 0 or R [1] == 0):
47             found += 1.0
48         total += 1
49 
50     print (found/total)
51 
52 choice_3 (102400)
53 choice_2 (102400)
54 choice_1 (102400)
55 choice_3 (102400)
56 choice_2 (102400)
57 choice_1 (102400)

 

输出:

0.334365234375
0.332392578125
0.333505859375
0.332177734375
0.33486328125
0.334150390625

 

思路来自

https://stackoverflow.com/questions/11356036/probability-simulation-in-python 

 

posted on 2022-10-31 09:49  yun@dicom  阅读(236)  评论(0编辑  收藏  举报