我对python还很陌生,正在为全班解决一个问题。我觉得我真的很接近解决方案,但我的数字仍然没有达到我期望的概率。你知道吗
在这个问题上,我们有一个包里面有两个芯片。我们知道一个芯片是白色的,另一个不是黑色就是白色。这些条件在我们每次玩游戏时都是真实的。你知道吗
在游戏中,我们从袋子里取出一个芯片,它是白色的。问题是写一个函数,它近似于从袋子里取出两个白色筹码的概率。函数的参数是我们玩游戏的次数。你知道吗
以下是我迄今为止编写的代码:
def prob_two_whites(num):
counter = 0 #counts the number of iterations or games played
first_white = 0 #counts how many times the first pull was white
double_white = 0 #counts how many times the second pull was white, if the first was also white
while counter < num: #runs a game until total number of games is reached
chip_1 = "white" #this is the chip we know is white
chip_2 = np.random.choice(["white","black"]) #chip two has an equal chance of being white or black for each game
result = np.random.choice([chip_1, chip_2], 2, replace = False) #drawing both chips without replacement
if result[0] == "white": #if the first chip pulled is white
first_white += 1 # add one to the first white
if result[1] == "white": #if the second pull was white, given the first was also white
double_white += 1 # add one to double_white
counter +=1 #add one to the counter
return (float(double_white)/float(first_white)) / (float(first_white)/float(counter))
实际上,结果应该是大约66.66%
从概率上讲,第一次被拉的可能性是75%。一旦第一次拔出白色,第二次拔出白色的可能性约为50%。你知道吗
当我观察第一个白色和两个白色的不同计数时,第一个白色的数字似乎和它们应该的一样(大约占总数的75%),但是我的两个白色计数总是太高。我觉得我的代码很直截了当,但不知怎么的,我似乎比我应该数的还要多。你知道吗
任何人能提供任何帮助都将不胜感激!你知道吗
谢谢你!你知道吗
问题不在于随机数的产生或计数,而在于最后的概率计算。你知道吗
假设第一个结果是白色的,得到两个白色结果的条件概率是
double_white / first_white
(简单地除以两个计数)。这是它们独立概率之比的简化形式:(double_white / count) / (first_white / count)
(注意,count
可以被抵消)通常,贝叶斯定律会说,在除以这些概率或计数时,分子中需要有一个额外的项。但是当它发生时,额外的项是反向条件概率(如果两个芯片都是白色的,那么第一个芯片是白色的概率),即100%(或者
1
)。与1
相乘没有任何作用,因此可以将其排除在计算之外。你知道吗我省略了上面所有的
float
调用,这既是为了清楚起见,也是因为它们确实不必要。如果您使用的是python3,那么在默认情况下,两个整数之间的除法将生成一个float
结果(您可以通过使用//
楼层除法操作符显式请求整数除法)。如果您仍然无法使用python2,那么如果您将from __future__ import division
放在文件的顶部,就可以获得python3行为(我强烈建议这样做!)。你知道吗相关问题 更多 >
编程相关推荐