我正在用 Python 來回答這個問題,即一群外星人是否應(yīng)該帶來 500 萬人口和 100 萬資源負(fù)載 vs 1M 人口和 500 萬負(fù)載......我試圖找出哪個這兩種選擇將使 200 年后新星球上的人口最大化。這是我的代碼:這是我的導(dǎo)數(shù)函數(shù)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]在這里,我定義了我的參數(shù):# model parametersa = 0.02 # related to conversion of unallocated resources into populationb = 0.0001 # related to growth of knowledgeW0 = 0.0 # initial amount of knowledge# time periodTmax = 600 # years這是我運行 odeint 并繪制結(jié)果的位置:# Put your code heret = np.arange(0, Tmax, 0.1)P0 = 5R0 = 1y0 = [P0,R0,W0]soln = odeint(derivs3, y0, t)PSol = soln[:, 0]RSol = soln[:, 1]WSol = soln[:, 2]P0 = 1R0 = 5y0 = [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")這就是問題出現(xiàn)的地方: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:所以它返回以下打印語句,這些語句與我得到的圖表不一致。這可能是索引的問題,但我使用 PSol[200] 和 PSol2[200] 因為我想知道如果他們想在 200 年后最大化人口,他們應(yīng)該帶多少外星人和資源。見下文(忽略大約 600 年的線,因為我沒有調(diào)整它們,知道它們會返回相同的問題):這是圖表。我知道這是對的(詢問幫助室),所以它必須是關(guān)閉的索引值。
1 回答

嚕嚕噠
TA貢獻1784條經(jīng)驗 獲得超7個贊
我沒有看到t您的代碼中定義的位置,但問題似乎是(如您所建議的)來自t[200] != 200. 只需添加print t[200]一行,這將相對容易檢查。
如果情況確實如此,您將需要確定哪個索引t==200或進行插值。我傾向于使用numpy.interp 進行插值,因為這將允許您調(diào)查不是時間步長整數(shù)倍的時間。
PSol_200 = np.interp(200, t, PSol)
PSol2_200 = np.interp(200, t, PSol2)
編輯: 通過您最近的編輯,我們可以看到您的時間步長是 0.1 而不是 1,因此t==200應(yīng)該出現(xiàn)在索引 2000 而不是 200。您正在比較 20 年后而不是 200 年后的人口。
添加回答
舉報
0/150
提交
取消