2020-04
17
51%的概率
思路很简单,但要得出这个概率结论要重复多少次呢?脚本写好以后我先用了10次,100次,1000次,效果都不好,数字太漂浮,于是我都怀疑自己了。搜索之后发现别人用MATLAB写了个大体意思跟我一样的程序,他重复了100万次,好吧,我懂了!本来这种扔随机数进去的测试重复就应该趋向于无穷,但试过你就知道,100万次绝对让你的电脑卡到怀疑死机了。所以我狡猾地控制百分数只输出整数,10万次有点卡(我的破电脑等待结果大概需要4秒),但还可以接受。
Exercise 8:This exercise pertains to the so-called Birthday Paradox, which you can read about at http://en.wikipedia.org/wiki/Birthday_paradox. If there are 23 students in your class, what are the chances that two of you have the same birthday? You can estimate this probability by generating random samples of 23 birthdays and checking for matches. Hint: you can generate random birthdays with the randint function in the random module. You can download my solution from http://thinkpython2.com/code/birthday.py.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import random def chance(num): n = 0 x = 100000 # 越大越好,但太大了运行慢到怀疑人生…… 1W小卡,10W卡,100W非常卡! for i in range(x): birth = [] for i in range(num): birth.append(random.randint(1, 365)) birth.sort() for i in range(num - 1): if birth[i] == birth[i+1]: n += 1 break return n/x num = 23 print('chance is', '{:.0%}'.format(chance(num))) # chance is 51% x = 10W 百分数显示小数将会是个测试噩梦!!! |
还没有评论