Langfao Langfao - 14 days ago 10
Python Question

Python: Loop not giving desired result

So I'm trying to write a code that simulates a predator and prey situation where it starts off with a low population of predators and high population of prey. Over time the predator population grows while the prey population shrinks until the prey population is too little to sustain the predator population. The predator population dies off and then the prey population is able to repopulate. The simulation is supposed to stop whenever one of the two populations reach 0, in this case the predator population will and plot two populations over time of the simulation until it stopped. This is my code so far:

import matplotlib.pyplot as plt

def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate):
preyCounts = []
predatorCounts = []
predatorI = initialPred
preyI = initialPrey
predator = predatorI
prey = preyI



while predator > 0 and prey > 0:

predator = predatorI * (1 - predShrink + predFedBirthRate * preyI)
prey = preyI * (1 + preyGrowth - predationRate * predatorI)
predatorCounts.append(predator)
preyCounts.append(prey)
predatorI = predator
preyI = prey


plt.plot(predatorCounts, 'r', preyCounts, 'b')
plt.show()

return preyCounts, predatorCounts

simulate(50,1000,0.25,0.01,0.05,0.00002)


Its output is this
:enter image description here

But it's supposed to come out like this:
enter image description here

Can someone help me please?

*Also aside from this whenever I put my plotting code outside of the function after the function line with values inside like this:

simulate(50,1000,0.25,0.01,0.05,0.00002)
plt.plot(predatorCounts, 'r', preyCounts, 'b')
plt.show()


It doesn't plot the values from the function and says
predatorCounts
and
preyCounts
are undefined.

pjs pjs
Answer

If I initialize your plot data with the starting populations and use int() truncation for the populations, I get the plot you say you're supposed to see:

import matplotlib.pyplot as plt

def simulate(initialPred, initialPrey, preyGrowth, predationRate, predShrink, predFedBirthRate):
    preyCounts = [initialPrey]
    predatorCounts = [initialPred]
    predator = initialPred
    prey = initialPrey

    while predator > 0 and prey > 0:
        predatorScaleFactor = 1.0 - predShrink + predFedBirthRate * prey
        preyScaleFactor = 1.0 + preyGrowth - predationRate * predator
        predator = int(predator * predatorScaleFactor)
        prey = int(prey * preyScaleFactor)
        predatorCounts.append(predator)
        preyCounts.append(prey)

    plt.plot(predatorCounts, 'r', preyCounts, 'b')
    plt.show()

    return preyCounts, predatorCounts

simulate(50, 1000, 0.25, 0.01, 0.05, 0.00002)