Created
August 18, 2021 02:49
-
-
Save jaymody/922480427473cf752417c06518590064 to your computer and use it in GitHub Desktop.
A simulation for the TedEd frog riddle: https://www.youtube.com/watch?v=cpwSGsb-rTs
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 random | |
N = 1000000 # number of frogs of each gender | |
assert N >= 2 # there must be at least 2 frogs of each gender | |
frogs = ["M"] * N + ["F"] * N | |
max_num_simulations = 2000000 # number of simulations to run | |
num_simulations = 0 | |
num_clearing_successes = 0 | |
num_log_successes = 0 | |
while num_simulations < max_num_simulations: | |
f = random.sample(frogs, 3) # randomly select 3 frogs from population | |
log_frog = f[0] # the log frog is always the first frog | |
clearing_frogs = [f[1], f[2]] # the other two frogs are clearing frogs | |
if "M" in clearing_frogs: # if there is at least one male in the clearing | |
if "F" == log_frog: # if the log frog is a female | |
num_log_successes += 1 | |
if "F" in clearing_frogs: # if at least one of the clearing frogs is a female | |
num_clearing_successes += 1 | |
num_simulations += 1 | |
if num_simulations != 0 and num_simulations % 100000 == 0: | |
print( | |
f"{num_simulations}, " | |
f"{num_clearing_successes / num_simulations:.5f}, " | |
f"{num_log_successes / num_simulations:.5f}" | |
) | |
print("\n\n--- final results ---") | |
print("Prob Survival with 1 Frog: ", num_log_successes / num_simulations) | |
print("Prob Survival with 2 Frogs: ", num_clearing_successes / num_simulations) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment