简体   繁体   中英

How to plot recursive function in matplotlib.pyplot?

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM