Created
April 20, 2024 14:59
-
-
Save tempodat/af04c33752fa0953ab124699cc0fe52b to your computer and use it in GitHub Desktop.
N rabbits in a bag - numerical solution
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
| """ | |
| A numeric solution for a probability question I thought about, | |
| It's similar to a "n marbles in a bag" type question: If I had | |
| some rabbits that grow year by year, and every year I chose one | |
| rabbit at random, noted its age and replaced it with a baby) | |
| so out of N integers (each rabbits age), one of them gets swapped | |
| with zero and then they all grow by one. What's the average age | |
| of the rabbits i'm pulling out? | |
| """ | |
| from random import randint | |
| from math import log10 | |
| n = 30 | |
| loops = int(10**7) | |
| rabbits = [0]*n | |
| average = 0 | |
| for i in range(loops): | |
| rabbits = [x+1 for x in rabbits] | |
| index = randint(0, n-1) | |
| average += rabbits[index] | |
| rabbits[index] = 0 | |
| if i % int(loops/100) == 0: | |
| cur = average/(i+1) | |
| print(f"{i}/{loops} ({int(100*i/loops)}%) => average={cur:.2f}, distance from expected value=10e{log10(abs(n-cur)):.2f}") | |
| average /= loops | |
| print(f"average age={average} (expected {n})") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment