I'm writing a recursive function to analyze various species population growth over time. I have four parameters: The initial population of the species in the first year (a), the year where I want to see what the population will be in years to come (b), the growth rate in a percentage (c) and lastly the maximum amount of the certain species the environment can handle (d).
(Population growth formula I am using is (a * b-1 + c) * (a *b-1) * 1 - (a * b-1/d))
So far this is what I have:
def animal_growth(a,b,c,d):
growth = (a * b-1 + c) * (a *b-1)
max_growth = growth * 1 - (a * b-1/d)
if a > 10000:
return
else:
return max_growth
animal_growth(200,20,0.05,5000)
So in the above example, I'm looking to find how long it will take for the animal population to exceed 5000 at a growth rate of 5% per 'year', long with what that population will be in 20 years, starting with the population at 200.
I was hoping to get a console output something like:
8.4 # how long it will take to exceed 5000
6000 # the population after 20 years
# neither of these might be correct so if there are different answers no worries
I'm stuck on the recursive end of things, the formulas and math I understand.
Thank you for your help!
The function you need is something like this:
def animal_growth(growth,year,rate,max_growth, years=0):
growth = (growth + (growth*rate))
if growth < max_growth:
years += 1
if years == year:
print (growth)
return animal_growth(growth, year, rate, max_growth, years)
else:
return (1 + years)
print(animal_growth(200,20,0.05,5000))
I think you should create 2 separate function, one to calculate the years it take to grow to a certain number, one to calculate how much it could grow given a certain number of years
def number_of_years_to_grow(initial, rate, max_growth):
growth = initial * (1 + rate)
if (growth <= max_growth):
return 1 + animal_growth(growth, rate, max_growth)
else:
return 1 # or return 0 (depending on whether you want to include the year where it exceed the maximum number or not)
def population_growth(initial, years, rate):
return initial * ((1 + rate) ** years)
print(number_of_years_to_grow(200, 20, 0.05))
print(animal_growth(200, 0.05, 5000))
Also, additional tips, please use a meaningful variable name for readability purpose.
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.