Skip to content

Instantly share code, notes, and snippets.

@vinimonteiro
Created November 24, 2020 12:21
Show Gist options
  • Save vinimonteiro/746bbed85fd506fcb6a66974afa20146 to your computer and use it in GitHub Desktop.
Save vinimonteiro/746bbed85fd506fcb6a66974afa20146 to your computer and use it in GitHub Desktop.
Monte Carlo Simulation in Basketball - Take the three or quick two
import random
trials = 10000
three_pc = 25
two_pc = 60
opp_two_pc = 65
opp_ft_pc = 65
time_to_shoot_two = 5
time_to_foul = 5
offense_rb_pc = 25
ft_rb_pc = 15
overtime_win_pc = 50
def sim_take_three():
if three_pc >= random.randint(0, 100):
if overtime_win_pc >= random.randint(0, 100):
return True # Winning
return False # Either missed the three or lost in overtime
def sim_take_two():
have_ball = True
points_down = 3
time_left = 30
while time_left > 0:
if have_ball:
# If down by 3 or more, make quick two.
# If down by 2 or less, explore entire time
if points_down >= 3:
time_left -= time_to_shoot_two
else:
time_left = 0
if two_pc >= random.randint(0, 100):
points_down -= 2
have_ball = False
else:
if offense_rb_pc >= random.randint(0, 100):
have_ball = False
else:
if points_down > 0:
time_left -= time_to_foul
# two free throws
if opp_ft_pc >= random.randint(0,100):
points_down += 1
if opp_ft_pc >= random.randint(0,100):
points_down += 1
have_ball = True
elif ft_rb_pc >= random.randint(0,100):
have_ball = True
else:
if opp_two_pc >= random.randint(0,100):
points_down += 2
time_left = 0
if points_down > 0:
return False
elif points_down < 0:
return True
else:
if overtime_win_pc >= random.randint(0,100):
return True
else:
return False
def simulate():
wins_taking_three = 0
wins_taking_two = 0
for trial in range(trials):
if sim_take_three():
wins_taking_three+=1
if sim_take_two():
wins_taking_two+=1
print(f'Wins taking the three: {wins_taking_three}')
print(f'Wins taking the two: {wins_taking_two}')
simulate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment