我在Python中创建了一个(相当复杂的)MontyHall模拟,但是,运行时,切换和不切换的几率相等,而不是,当我知道,实际上,情况并非如此。怎么了?
import math
import random
Right = 0
def TestWithSwitch():
global Right
wdoor = math.floor(random.random() * 3)
doors = [0,0,0]
doors[wdoor] = 1
Ldoors = [0,0]
i=0
##Declare winning door to be the winning door in the door Array
for x in range(0, 3):
if(x!=3):
if(doors[x] != 1):
Ldoors[i] = x
i+=1
##Chose the losing doors to be the doors that aren't the winning door
choice = math.floor(random.random() * 3)
DoorOut = 0
##Pick a Choice
LChose = False
for y in range(0, 2):
if(y!= 2):
if(Ldoors[y] == choice):
DoorOut = Ldoors[(y+1)%2]
LChose = True
if(LChose == False):
DoorOut = Ldoors[math.floor(random.random() * 2)]
Reserved = [DoorOut, choice]
##DoorOut is chosen from any of the losing doors we didn't pick as our choice, and is the door the computer is told doesn't have the prize
for z in range(0, 3):
if(z!= 3):
if(z in Reserved == False):
choice = z
##Make our new choice the other choice that we didn't previously choose
if(choice == wdoor):
Right+=1
def TestNoSwitch():
global Right
wdoor = math.floor(random.random() * 3)
doors = [0,0,0]
doors[wdoor] = 1
Ldoors = [0,0]
i=0
for x in range(0, 3):
if(x!=3):
if(doors[x] != 1):
Ldoors[i] = x
i+=1
choice = math.floor(random.random() * 3)
if(choice == wdoor):
Right+=1
for j in range(1, 10000):
## TestWithSwitch() and TestNoSwitch() both result in about 1/3. You can test by putting either function in.
if(j == 9999):
print(Right/10000)
我知道,转换应该返回66%的几率,而不应该返回33%的几率。我所得到的几率甚至不到100%,而是大约三分之二,这是不可能的概率。
问题在于:
这将被计算为chained comparison,结果总是错误的。在
^{pr2}$使用括号创建右运算符顺序:
^{3}$或者最好使用明确的“不在”运算符:
首先
另一方面,通过全局变量收集函数结果有点邪恶。在
我可以这样做:
^{pr2}$产生的输出
^{3}$注意:您可以通过任意地将
guess = pick()
替换为guess = "A"
来加快它的速度(不损失通用性)。在相关问题 更多 >
编程相关推荐