Reputation: 179
I am trying to write a predator-prey model where I take the input for the amount of rabbits, foxes, and years. Then output the final number of rabbits and foxes after that amount of years. I am able to return an amount of rabbits and foxes, but I am not getting the correct values. The algorithm for the foxes and rabbits after one year are:
F1yr = F0yr – Floor(F0yr * (G-S * R0yr))
R1yr = R0yr + Floor( R0yr * (A-B * F0yr))
Where A = 0.04, B = 0.0005, G = 0.2, and S=0.00005
For a starting input of 5891 rabbits and 16 foxes after 99 years, it should return 6484 rabbits and 144 foxes, but I am getting 4682 rabbits and 189 foxes.
This is the code that I have so far, I feel like I am close to the answer, but not fully there:
def bunnies(rabbits,foxes,years):
if __name__ == '__main__':
if years == 0:
tot = []
tot.append(rabbits)
tot.append(foxes)
return tot
else:
a = 0.04
b = 0.0005
g = 0.2
s = 0.00005
rabbits = rabbits + math.floor(rabbits * (a-b * foxes))
foxes = foxes - math.floor(foxes * (g-s * rabbits))
return bunnies(rabbits,foxes,years-1)
rabbits = int(input('Enter Initial Rabbit Population:\n'))
foxes = int(input('Enter Initial Fox Population:\n'))
years = int(input('Enter Number of Years to Simulate:\n'))
print(bunnies(rabbits,foxes,years))
Upvotes: 1
Views: 569
Reputation: 24048
Your code was almost correct, here is a fixed and cleaned up version:
import math
def bunnies(rabbits, foxes, years):
A = 0.04
B = 0.0005
G = 0.2
S = 0.00005
if years == 0:
return rabbits, foxes
else:
rabbits_last, foxes_last = rabbits, foxes
foxes = foxes_last - math.floor(foxes_last * (G - S * rabbits_last))
rabbits = rabbits_last + math.floor(rabbits_last * (A - B * foxes_last))
return bunnies(rabbits, foxes, years - 1)
if __name__ == '__main__':
rabbits = int(input('Enter Initial Rabbit Population: '))
foxes = int(input('Enter Initial Fox Population: '))
years = int(input('Enter Number of Years to Simulate: '))
print(bunnies(rabbits, foxes, years))
The problem ocurred when you used the already changed value of the rabbit population for the new fox population count.
You also used wrong variable names when calling print(bunnies(rab,fox,yrs))
, but I think that was just a copying mistake since you didn't get error messages.
Lastly your if __name__ == '__main__'
shouldn't have been inside the function but on the module scope like I have it.
Upvotes: 5