Python 如何使用递归计算一个数字达到最大值需要多长时间?

Python 如何使用递归计算一个数字达到最大值需要多长时间?,python,recursion,Python,Recursion,我正在写一个递归函数来分析不同物种种群随时间的增长。我有四个参数:第一年物种的初始数量(a),我想知道未来几年种群数量的年份(b),以百分比表示的增长率(c),最后是环境能够处理的特定物种的最大数量(d) (我使用的人口增长公式是(a*b-1+c)*(a*b-1)*1-(a*b-1/d)) 到目前为止,这就是我所拥有的: def animal_growth(a,b,c,d): growth = (a * b-1 + c) * (a *b-1) max_growth = growt

我正在写一个递归函数来分析不同物种种群随时间的增长。我有四个参数:第一年物种的初始数量(a),我想知道未来几年种群数量的年份(b),以百分比表示的增长率(c),最后是环境能够处理的特定物种的最大数量(d)

(我使用的人口增长公式是(a*b-1+c)*(a*b-1)*1-(a*b-1/d))

到目前为止,这就是我所拥有的:

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)
因此,在上面的例子中,我想知道动物种群以每年5%的增长率超过5000只需要多长时间,以及20年后的种群数量,从200只开始

我希望得到一个控制台输出,比如:

  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
我被困在事物的递归端,我理解的公式和数学


谢谢你的帮助

我认为您应该创建两个单独的函数,一个用于计算增长到某个数字所需的年数,另一个用于计算在给定的年数下它可以增长多少

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))
def增长年数(初始、速率、最大增长):
增长=初始*(1+速率)

如果(生长您需要的功能如下:

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))
def动物生长(生长、年份、速率、最大生长、年份=0):
增长=(增长+(增长*率))
如果增长小于最大增长:
年+=1
如果年==年:
印刷品(增长)
回归动物生长(生长、年、率、最大生长、年)
其他:
回报率(1年以上)
印刷品(动物生长(200,20,0.055000))

你想计算时间吗?根据什么标准,是一年吗?我想计算达到5000需要多长时间,如果可能的话,20年后人口会是多少。但第一个更重要。**编辑:是的,我想计算年。你在代码示例中的做法对我来说有点不舒服,你应该计算增长并将其添加到初始人口中,这样你可以增加b。这是时间,我做了,但增长已经在第一个循环中超过5000,所以