import math
import random
import matplotlib.pyplot as plt
import seaborn as sns
# A list of g goats' floor preference.
def goatPreferences(g) :
preferences = []
for i in range(1, g+1):
#Goat's preference can be any from floor 1 to floor g.
preferences.append(random.randrange(1, g+1))
preferences.sort()
return(preferences)
def compareFloor(g, preferences):
floors = list(range(1, g+1))
for i in range(g-1, -1, -1) :
#Compare goat preference with current floor.
if preferences[i] > floors[i] :
return(0)
else :
preferences.pop()
floors.pop()
return(1)
def monteCarlo(g):
outcomes = 0
for i in range(1000000000):
preferences = goatPreferences(g)
outcome = compareFloor(g, preferences)
outcomes += outcome
return(outcomes)
numerators = []
for i in range(1, 12):
print(i-1)
outcomes = monteCarlo(i)
numerators.append(outcomes)
0 1 2 3 4 5 6 7 8 9 10
approximations = []
for i in range(1, 12):
a = ((i+1)**(i-1)) / i**i
approximations.append(a)
#Plot.
sns.set()
fig = plt.figure(figsize = (14, 8))
ax = fig.add_subplot(111, xlim = (0.5, 11.5), ylim = (0, 1))
simulation = [n/1000000000 for n in numerators]
#Scatter.
ax.scatter(x = range(1, 12),
y = simulation,
s = 100,
c = "#287D8E")
# ax.scatter(x = range(1, 12),
# y = approximations,
# s = 50,
# alpha = 0.5,
# c = "#481567")
#Title.
ax.set_title("Probability All Goats Will Have Their Own Floor (1,000,000,000 simulations)", fontsize = 24)
#Axes.
ax.set_xlabel("Goats", fontsize = 20)
ax.set_ylabel("Probability", fontsize = 20)
ax.tick_params(axis = 'both', labelsize = 16)
fig.savefig("2022.06.24 Classic.png")
print(numerators)
print("")
print(approximations)
[1000000000, 750004596, 592558973, 488287741, 414732100, 360210095, 318294739, 285087681, 258127130, 235781540, 217040838] [1.0, 0.75, 0.5925925925925926, 0.48828125, 0.41472, 0.36023233882030176, 0.3183124621300891, 0.2850871682167053, 0.2581174791713197, 0.2357947691, 0.21701658432479423]