1

我遇到了一个困境,因为 for i in range(x) 循环没有迭代。我的程序的目的是模拟狐狸和兔子在岛上的相互作用,并在每天之后打印出每种动物的种群。我知道方程式是正确的,我遇到的问题是我的循环只会在大范围内运行一次。

我的代码:

def run_simulation():
    print()
    RABBIT_BIRTH_RATE = 0.01
    FOX_BIRTH_RATE = 0.005
    INTERACT = 0.00001
    SUCCESS = 0.01
    x = 0
    y = 1
    FOXES = eval(input("Enter the initial number of foxes: "))
    print()
    RABBITS = eval(input("Enter the initial number of rabbit: "))
    print()
    DAYS = eval(input("Enter the number of days to run the simulation: "))
    print()
    print("Day\t","Rabbits\t","Foxes\t")
    print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")
    for i in range(DAYS):
        RABBITS_START = round((RABBIT_BIRTH_RATE * RABBITS) - (INTERACT * RABBITS * FOXES))
        FOXES_START = round((INTERACT * SUCCESS * RABBITS * FOXES) - (FOX_BIRTH_RATE * FOXES))
        y = y + x
        print (y,"\t",(RABBITS_START+RABBITS),"\t","\t",(FOXES_START+FOXES),"\t")
run_simulation()

当以 500 只狐狸、10000 只兔子和 1200 天的示例运行时,我的输出将如下所示

Day  Rabbits     Foxes  
0    10000       500    
1    10050       498 

第二条输出线重复剩余的 1199 次。任何帮助将不胜感激我无法弄清楚我做错了什么。

4

3 回答 3

3

你在开始时设置RABBITSRABBIT_BIRTH_RATE。然后,在每次循环迭代中,您都设置RABBITS_START了一些涉及这两个数字的公式。你永远不会改变RABBITSorRABBIT_BIRTH_RATEFOXESor 的值,所以每次你运行循环时,你只是用相同的数字再次计算相同的东西。您需要在每次迭代时更新变量的值——也就是说,为 、 等设置一个新RABBITSFOXES

于 2013-09-13T19:22:48.453 回答
2

对我来说最大的问题是您将“兔子/狐狸的变化”命名为什么。RABBITS_START听起来像是 的初始计数RABBITS,但事实并非如此。这就是我将其重命名为 的原因RABBITS_DELTA,因为它实际上是在计算兔子每天的变化。

我想我明白了。至少现在这更像是一个模拟:

def run_simulation():
  RABBIT_BIRTH_RATE = 0.01
  FOX_BIRTH_RATE = 0.005
  INTERACT = 0.00001
  SUCCESS = 0.01
  x = 0
  y = 1

  FOXES = eval(str(input("Enter the initial number of foxes: ")))
  RABBITS = eval(str(input("Enter the initial number of rabbits: ")))

  DAYS = eval(str(input("Enter the number of days to run the simulation: ")))

  print("Day\t","Rabbits\t","Foxes\t")
  print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")

  count = 0
  while count < DAYS:
    RABBITS_DELTA = round((RABBIT_BIRTH_RATE * RABBITS) \
                          - (INTERACT * RABBITS * FOXES))
    FOXES_DELTA = round((INTERACT * SUCCESS * RABBITS * FOXES) \
                        - (FOX_BIRTH_RATE * FOXES))
    y = y + x

    RABBITS += RABBITS_DELTA
    FOXES += FOXES_DELTA
    print (y,"\t",(RABBITS),"\t","\t",(FOXES),"\t")

    count += 1


run_simulation()
于 2013-09-13T19:38:17.300 回答
1

我将尝试解释您的意思:

for i in range(1, DAYS + 1):
    rabbit_delta = ... # RABBITS_START
    fox_delta = ... # FOXES_START
    RABBITS += rabbit_delta
    FOXES += fox_delta
    print(i, "\t", RABBITS, "\t\t", FOXES, "\t")

根据其他人的答案进行编辑。(野刺不太野。)

有关散文中的解释,请参阅 BrenBarn 的答案。

于 2013-09-13T19:25:13.590 回答