我正在用Python来回答这个问题,一组外星人是否应该带来500万人口和100万资源负载,而不是100万人口和500万负载。。。我正试图找出这两个选项中的哪一个能在200年后最大限度地增加一个新星球上的人口。这是我的密码:
这是我的导数函数
def derivs3(y1, t):
c = P0 + R0
r = a / c
q = (a + b) / c
Pi = y1[0]
Ri = y1[1]
Wi = y1[2]
# the model equations
dPdt = q * Pi*Ri/(1+Wi)
dRdt = - q * Pi*Ri/(1+Wi) + (a / q) * Wi / (t + .0001)
dWdt = b
return [dPdt, dRdt, dWdt]
在这里,我定义我的参数:
# model parameters
a = 0.02 # related to conversion of unallocated resources into population
b = 0.0001 # related to growth of knowledge
W0 = 0.0 # initial amount of knowledge
# time period
Tmax = 600 # years
下面是我运行odeint并绘制结果的地方:
# Put your code here
t = np.arange(0, Tmax, 0.1)
P0 = 5
R0 = 1
y0 = [P0,R0,W0]
soln = odeint(derivs3, y0, t)
PSol = soln[:, 0]
RSol = soln[:, 1]
WSol = soln[:, 2]
P0 = 1
R0 = 5
y0 = [P0,R0,W0]
soln = odeint(derivs3, y0, t)
PSol2 = soln[:, 0]
RSol2 = soln[:, 1]
WSol2 = soln[:, 2]
plt.plot(t,PSol)
plt.plot(t,PSol2)
plt.legend(("5Bil Aliens, 1Bil Resources","1Bil Aliens, 5Bil Resources"), loc='upper left', prop={'size':15}, bbox_to_anchor=(1,1))
plt.grid()
plt.xlabel("time (years)")
plt.ylabel("Population (billions)")
plt.title("Populations vs. Time")
这就是问题所在:
if PSol[200] > PSol2[200]:
print("To maximize population after 200 years (for a total of", round(PSol[200],2),"billion aliens), the aliens should take a population of 5 Billion Aliens, and a load of 1 Billion Resources.")
elif PSol[200] < PSol2[200]:
print("To maximize population after 200 years (for a total of", round(PSol2[200],2),"billion aliens), the aliens should take a population of 1 Billion Aliens, and a load of 5 Billion Resources.")
else:
print("The population after 200 years will be the same (for a total of", round(PSol2[200],2),"billion aliens), whether the aliens take a population of 5 Billion Aliens and a load of 1 Billion Resources, or a population of 1 Billion Aliens and a load of 5 Billion Resources")
所以它返回了下面的print语句,它们与我得到的图不一致。这可能是索引的问题,但我使用PSol[200]和PSol2[200],因为我想知道如果他们想在200年后最大化人口,他们应该带来多少外星人和资源。见下文(忽略600年前的那行,因为我没有调整他们,因为我知道他们会返回同样的问题):
这是图表。我知道这是对的(问帮助室),所以一定是索引值关闭了。你知道吗
我看不出代码中的
t
是在哪里定义的,但问题似乎是由t[200] != 200
引起的(正如您所建议的)。只需添加print t[200]
行就可以相对容易地检查这一点。你知道吗如果确实是这样,那么您需要确定
t==200
或插值的索引。我倾向于使用numpy.interp插值,因为这将允许您调查不是时间步长整数倍的时间。你知道吗编辑: 通过最近的编辑,我们可以看到timestep是0.1而不是1,因此
t==200
应该出现在索引2000而不是200处。你比较的是20年后的人口,而不是200年。你知道吗相关问题 更多 >
编程相关推荐