Skip to content

Instantly share code, notes, and snippets.

@koorukuroo
Created March 11, 2025 17:18
Show Gist options
  • Save koorukuroo/6b14a1642737512b69ef642f014df9c9 to your computer and use it in GitHub Desktop.
Save koorukuroo/6b14a1642737512b69ef642f014df9c9 to your computer and use it in GitHub Desktop.
import numpy as np
import time
def monty_hall_numpy(trials=100000000, switch=True):
"""
Fully vectorized Monty Hall simulation using NumPy for maximum performance.
Parameters:
trials (int): Number of games to simulate.
switch (bool): If True, the player switches doors; otherwise, they stay.
Returns:
float: Probability of winning when switching/staying.
"""
# Step 1: Randomly place the car behind one of the three doors
prize_doors = np.random.randint(0, 3, trials) # NumPy generates all at once
# Step 2: Players make initial random choices
chosen_doors = np.random.randint(0, 3, trials)
# Step 3: The host opens a door that is neither the chosen door nor the prize door
# Create a mask for available doors
all_doors = np.array([0, 1, 2]) # Three possible doors
# Vectorized way to choose host door
host_doors = np.zeros(trials, dtype=int)
for i in range(3): # Loop over door numbers (0, 1, 2)
mask = (chosen_doors != i) & (prize_doors != i) # Find valid doors for the host to open
host_doors[mask] = i # Assign a valid door for the host
# Step 4: Player switches (if switch=True)
if switch:
# The remaining door (not chosen, not opened by the host)
new_choices = 3 - chosen_doors - host_doors
chosen_doors = new_choices # Player switches
# Step 5: Calculate wins (where chosen door == prize door)
wins = (chosen_doors == prize_doors)
return np.mean(wins) # Probability of winning
# Measure execution time
tic = time.time()
# Run the fully vectorized Monty Hall simulation
win_probability = monty_hall_numpy(trials=100000000, switch=True)
toc = time.time()
# Print results
print(f"Winning probability when switching: {win_probability:.6f}")
print(f"Execution time: {toc - tic:.2f} seconds")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment