-1

这是我当前的代码

#this is the input for population and predators
popOne=float(input("Enter the predator population : "))  20

popTwo=float(input("Enter the prey population :")) 1000

#period is the amount of iterations, in my case 10
period=float(input("Enter the number of periods: ")) 10

#This is the values for the given periods
A=float(input("Enter the value .1: ")) .1
B=float(input("Enter the value .01 : ")) .01
C=float(input("Enter the value .01 : ")) .01
D=float(input("Enter the value .00002: ")) .00002

#Formluas from my book for prey population, and predator population

prey=(popTwo*(1+A-(B*popOne)))

pred=(popOne*(1-C+(D*popTwo)))

i=0
for i in range(10):
    print(prey)
    print(pred)
    i = i+1 

最后一部分是我遇到错误的地方。我无法让代码打印出第一次迭代并继续进行第二次、第三次等等。

另外,我怎样才能使输出看起来像:

After period 1 there are 20 predators
After period 1 there are 900 prey

After period 2 there are 20 predators
After period 2 there are 808 prey 

After period 3 there are 20 predators
After period 3 there are 724 prey

等等。

4

4 回答 4

0

您的代码存在许多问题:

  1. period应该被读取为整数,并且可能应该用于控制循环的范围。
  2. i由循环设置和更新,请勿尝试对其进行初始化或手动更新。
  3. pred和需要在循环的每次迭代中应用公式,prey即将它们移动到打印语句之前的循环中。他们也应该被int编辑。
  4. 在计算pred和之后prey,您需要相应地更新总体值popOnepopTwo
  5. 您应该将提示从"Enter the value .1: "更丰富、更通用的内容更改为"Enter the value for coefficient A: ".
于 2013-09-26T21:54:18.870 回答
0

您需要将人口更新代码放入循环中。我还建议对起始人口也使用predprey变量。这是一些代码:

pred = float(input("Enter the predator population : ")) # use pred and prey here
prey = float(input("Enter the prey population :"))

periods = int(input("Enter the number of periods: "))

A=float(input("Enter the value .1: ")) # these should have better prompts
B=float(input("Enter the value .01 : "))
C=float(input("Enter the value .01 : "))
D=float(input("Enter the value .00002: "))

for i in range(periods):
   # update both pred and prey at once (so no temp vars are needed)
   # also, lots of unneeded parentheses were removed
   prey, pred = prey*(1 + A - B*pred), pred*(1 - C + D*prey)

   print("After period {} there are {:.0f} predators, and {:.0f} prey"
         .format(i, pred, prey))
于 2013-09-26T21:54:36.917 回答
0

我不是 100% 清楚你想要做什么,但我觉得为 prey 和 pred 分配值的行应该在你的循环中?

我还认为计算 prey 和 pred 值的公式会使用 prey 和 pred 的当前值,而不是用户输入的初始值?

于 2013-09-26T21:48:03.607 回答
0

这个简单的代码将显示一个捕食者猎物模型

import matplotlib.pyplot as plt
import numpy as np

人口数据

print "Enter the population of the prey:"
prey = float(input());

print "Enter the population of the predator:"
pred = float(input());

print "Enter Simulation Time in seconds:"
simulation_time = int(input())

time = 0.0
t = []
dt = 0.05

A = .1
B = .01
C = .01
D = 0.00002


while time < simulation_time:
    prey = (prey*(1+A-(B*pred)))
    pred=(pred*(1-C+(D*prey)))
    time = time +dt

print("After {} seconds there are {:.0f} predators, and {:.0f} prey" .format(simulation_time, pred, prey))
于 2016-02-18T22:00:20.977 回答