Created
November 16, 2022 16:27
-
-
Save samsonq/913629465736f01b8c1080d02b30b143 to your computer and use it in GitHub Desktop.
Monty Hall Problem Simulation
This file contains 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
import numpy as np | |
def monty_hall(): | |
doors = np.array([1, 0, 0]) | |
np.random.shuffle(doors) | |
initial_choice = np.random.randint(len(doors)) | |
goat_door = 0 | |
for i in range(len(doors)): | |
if i == initial_choice: | |
continue | |
elif doors[i] == 0: | |
goat_door = i | |
break | |
switch_choice = 3-(initial_choice+goat_door) | |
return doors[initial_choice]==1, doors[switch_choice]==1 | |
def monte_carlo_simulation(n=10000): | |
no_switch_results = [] | |
switch_results = [] | |
for _ in range(n): | |
no_switch, switch = monty_hall() | |
no_switch_results.append(no_switch) | |
switch_results.append(switch) | |
return sum(no_switch_results)/n, sum(switch_results)/n | |
if __name__ == "__main__": | |
switch, no_switch = monte_carlo_simulation() | |
print("Probability of winning with switching: {}".format(switch)) | |
print("Probability of winning with no switching: {}".format(no_switch)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment