Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using numpy array #3

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# frog_problem
Here is the frog problem code I wrote in an Edinburgh pub.

Feel free to make better version. This one has not changed since I wrote it. V1 was the same code but saved before I changed it to work for different distances so I have not bothered upload it as well (it was still very unifinished).
It uses numpy arrays to simulate multiple frogs.
The answer to how many jumps the frog needs to do to reach the end is quite clear :)

Video is here: https://youtu.be/ZLTyX4zL2Fc
Original Video is here: https://youtu.be/ZLTyX4zL2Fc
38 changes: 0 additions & 38 deletions frog-2.py

This file was deleted.

64 changes: 64 additions & 0 deletions frog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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()