0

I'm trying to plot a recursive function I had made that measures growth over time. Here is the function:

def pop(start_pop, years, percentage_change, max_pop):
    if years == 0:
         return start_pop
    else:
         changes = pop(start_pop,years-1,percentage_change,max_pop)
         return changes + (1-changes/max_pop)*percentage_change*changes

print(pop(600,85,0.1,20000))

Which gives me the output of:

19879.4425

How can I plot this function of the graph, where "years" is on the x-axis and "max_pop" is on the y-axis?

Thanks for your help!

Note: If it helps, I'm wanting/ expecting once plotted that the curve will look something similar to a learning curve.

2
  • 1
    If you want to plot a function f(x, otherargs) at values x = [1,2,3,...] you evaluate the function on the list, e.g. y = [f(i, otherargs) for i in x] and plot plt.plot(x,y). Commented Nov 7, 2018 at 17:25
  • To add to @ImportanceOfBeingErnest, since it's a recursive function it keep calculating from 1. It will be helpful if you have a global cache so you don't do a lot of repeating calculation. Commented Nov 7, 2018 at 17:33

1 Answer 1

1

You could just add a list at the top:

import matplotlib as mpl
import matplotlib.pyplot as plt
changes_plot=[]
def pop(start_pop, years, percentage_change, max_pop):
    if years == 0:
         return start_pop
    else:
        changes = pop(start_pop,years-1,percentage_change,max_pop)
        changes_plot.append(changes)
        return changes + (1-changes/max_pop)*percentage_change*changes

pop(600,85,0.1,20000)
plt.plot(changes_plot)
plt.show()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is what I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.