import matplotlib.pyplot as plt def populations(prey0,pred0,growth,predation,conversion,death,years,stepsPerYear,starveCutoff,starveRate): """Returns the predicted populations of two species, given their initial populations, the prey's growth rate, the predation rate, the predator's food conversion rate, the predator's death rate, and the number of years to predict. stepsPerYear determines how many populations will be computed per year, with larger values giving more accurate calculations.""" times = [0] prey = [prey0] pred = [pred0] for y in range(years*stepsPerYear): times.append(float(y)/stepsPerYear) #prey.append(prey[y] + prey[y] * (growth-predation*pred[y])/stepsPerYear) prey.append(prey[y] + prey[y] * (growth-predation*pred[y]-starvation(prey[y],starveCutoff,starveRate))/stepsPerYear) pred.append(pred[y] + pred[y] * (conversion*prey[y]-death)/stepsPerYear) return times, prey, pred def starvation(prey,cutoff,rate): if prey < cutoff: return 0 else: return rate def plotPopulations(times,prey,pred,preyname,predname): """Displays a plot of two populations over the given times.""" preyPlot = plt.plot(times, prey, '-' ) #solid line predPlot = plt.plot(times, pred, ':' ) #dotted line plt.legend( (preyPlot, predPlot), (preyname, predname), 'best') #best location plt.xlabel('Years') plt.ylabel('Population') plt.title('Predator-Prey Model') plt.show() times, prey, pred = populations(100,50,.5,.0025,.002,.6,30,500,500,1.0) plotPopulations(times,prey,pred,"Hare","Lynx")