達(dá)令說(shuō)
2021-11-16 18:21:59
我正在用 Python 來(lái)回答這個(gè)問(wèn)題,即一群外星人是否應(yīng)該帶來(lái) 500 萬(wàn)人口和 100 萬(wàn)資源負(fù)載 vs 1M 人口和 500 萬(wàn)負(fù)載......我試圖找出哪個(gè)這兩種選擇將使 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這是我運(yùn)行 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")這就是問(wèn)題出現(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:所以它返回以下打印語(yǔ)句,這些語(yǔ)句與我得到的圖表不一致。這可能是索引的問(wèn)題,但我使用 PSol[200] 和 PSol2[200] 因?yàn)槲蚁胫廊绻麄兿朐?200 年后最大化人口,他們應(yīng)該帶多少外星人和資源。見(jiàn)下文(忽略大約 600 年的線,因?yàn)槲覜](méi)有調(diào)整它們,知道它們會(huì)返回相同的問(wèn)題):這是圖表。我知道這是對(duì)的(詢問(wèn)幫助室),所以它必須是關(guān)閉的索引值。
1 回答

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