Skip to content

Instantly share code, notes, and snippets.

@tom-galvin
Last active April 28, 2022 08:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tom-galvin/0e6073ecce62df2db467 to your computer and use it in GitHub Desktop.
Save tom-galvin/0e6073ecce62df2db467 to your computer and use it in GitHub Desktop.
A Python/matplotlib script to animate compound interest with an increasing number of terms
# Python code to generate an animation showing compound interest taking place with
# increasingly smaller terms. You will require matplotlib to run this code.
# You'll also require ImageMagick installed to generate the .gif animation.
# You can find this at http://usn.pw/blog/maths/2015/04/09/compound-interest
import matplotlib.pyplot as mp
import matplotlib.animation as ma
def gen_data(steps):
"""Creates the data to be plotted in this animation frame."""
x, y = [0.0], [1.0]
for _ in range(steps):
x.append(x[-1] + 1 / steps)
if steps < 1000:
# If the number of steps is less than 1000, then visually demonstrate the
# presence of "steps".
x.append(x[-1])
y.append(y[-1])
y.append(y[-1] * (1 + 1 / steps))
return x, y
limit_x, limit_y = [0, 1.02], [2.7183, 2.7183]
fig, axis = mp.subplots()
def frame(i):
"""Creates the animation frame."""
axis.cla()
axis.plot(*gen_data(i))
axis.plot(limit_x, limit_y, 'g--') # Show the actual value of e with a dotted green line
if i >= 1000: # If the number of intervals is 1000 or greater, assume infinity (if only)
display_intervals = "\u221e" # Unicode infinity, thank you Python 3!
else:
display_intervals = str(i)
axis.set_title("Limit of compound interest with %s intervals" % display_intervals)
axis.set_xlabel("Time")
axis.set_xlim([0, 1.2])
axis.set_ylabel("Value as fraction of initial value")
axis.set_ylim([0, 3])
animation = ma.FuncAnimation(
fig,
frame,
# The repeated values in the following array slow the animation down for key points.
# I don't know matplotlib well enough, so there may be a better way, but this works.
[1, 1, 1, 2, 2, 3, 4, 6, 10, 15, 20, 30, 50, 100, 150, 250, 1000, 1000, 1000, 1000],
interval=25,
blit=True)
animation.save(
'anim.gif',
writer='imagemagick',
fps=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment