小朋友问我一个问题, 如何用 Python 来模拟概率.
题目是: 从 [-2, -1, 0, 1, 2, 3] 中随机选择两个不同的数, 乘积为 0 的概率是多少?
我搜索并思考了一下, 得出以下两种方式:
choice_1 的思路是, 对列表进行深拷贝来模拟
choice_2 的思路是, 如果选到相同的数, 就放弃本次选择.
乘积为 0 用 (A1 == 0 or A2 == 0) 来判断, 性能方面可能快一点
1 import random 2 import copy 3 4 5 def choice_1 (trials): 6 7 total = 0 8 number = 0.0 9 10 lst = [-2, -1, 0, 1, 2, 3] 11 12 while total < trials: 13 14 A1 = random.choice (lst) 15 lstbk = copy.deepcopy (lst) 16 lstbk.remove (A1) 17 A2 = random.choice (lstbk) 18 19 if (A1 == 0 or A2 == 0): 20 number += 1.0 21 22 total += 1 23 24 print (number/total) 25 26 27 def choice_2 (trials): 28 29 total = 0 30 number = 0.0 31 32 lst = [-2, -1, 0, 1, 2, 3] 33 34 while total < trials: 35 36 A1 = random.choice (lst) 37 A2 = random.choice (lst) 38 if (A1 == A2): 39 continue 40 41 if (A1 == 0 or A2 == 0): 42 number += 1.0 43 44 total += 1 45 46 print (number/total) 47 48 49 choice_1 (102400) 50 choice_2 (102400) 51 choice_1 (102400) 52 choice_2 (102400) 53 choice_1 (102400) 54 choice_2 (102400)
输出:
0.335185546875
0.33296875
0.333583984375
0.33208984375
0.332392578125
0.333876953125
思路来自
https://stackoverflow.com/questions/11356036/probability-simulation-in-python
标签:概率,Python,102400,number,choice,A1,lst,total,模拟 From: https://www.cnblogs.com/yun-dicom/p/16843233.html