Created
November 4, 2021 15:47
-
-
Save thomasjungblut/fe9102e5a1592f8ba1a95c53345016c7 to your computer and use it in GitHub Desktop.
monty hall problem with monte carlo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import random as r | |
def random_doors(): | |
doors = [False] * 3 | |
doors[r.randint(0, 2)] = True | |
return doors | |
def choose_door(): | |
return r.randint(0, 2) | |
def reveal_door(doors, not_door): | |
for i in range(len(doors)): | |
if not doors[i] and i != not_door: | |
doors[i] = None | |
break | |
return doors | |
def choose_remaining_door(doors, door): | |
for i in range(len(doors)): | |
if doors[i] is not None and i != door: | |
return i | |
def run_experiment(switch): | |
win_count = 0 | |
total = 100000 | |
for i in range(total): | |
doors = random_doors() | |
door = choose_door() | |
if switch: | |
doors = reveal_door(doors, door) | |
door = choose_remaining_door(doors, door) | |
if doors[door]: | |
win_count += 1 | |
print("win chance when switch=%s: %f" % (switch, win_count / total)) | |
run_experiment(switch=False) | |
run_experiment(switch=True) | |
# prints | |
# win chance when switch=False: 0.334480 | |
# win chance when switch=True: 0.666830 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment