forked from standupmaths/frog_problem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrog.py
More file actions
64 lines (33 loc) · 1.33 KB
/
frog.py
File metadata and controls
64 lines (33 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import numpy as np
import matplotlib.pyplot as plt
randomGenerator = np.random.default_rng() # Require numpy v1.17+
ite = 1000 # Number of loops for the average
maxDistance = 1000
totalDist = np.arange(1, maxDistance)
randomLeap = np.empty_like(totalDist)
totalLeaps = np.zeros_like(totalDist)
for i in range(ite):
print(f" - Iteration {i+1}/{ite}", end="\r")
distLeft = totalDist.copy()
leaps = np.zeros_like(totalDist)
stillLeaping = np.ones_like(totalDist, dtype=bool)
while np.any(stillLeaping):
randomLeap[stillLeaping] = randomGenerator.integers(
1, distLeft[stillLeaping], endpoint=True)
np.subtract(distLeft, randomLeap, where=stillLeaping, out=distLeft)
leaps[stillLeaping] += 1
stillLeaping[distLeft == 0] = False # Arrived at the end
np.add(totalLeaps, leaps, out=totalLeaps)
print()
averageLeaps = totalLeaps/ite
A, B = np.polyfit(np.log(totalDist), averageLeaps, 1)
print(f"Average number of leaps ≈ {A:.5}*ln(Total distance)+{B:.5}")
plt.plot(totalDist, A*np.log(totalDist)+B, linewidth=2, label=f"y≈{A:.5}*ln(x)+{B:.5}")
plt.scatter(totalDist, averageLeaps, s=2, marker="*", color="green")
plt.grid(True)
# plt.xscale("symlog")
plt.xlabel("Total distance")
plt.ylabel("Leaps")
plt.legend()
plt.title("Average number of leaps")
plt.show()