這是我在這裏的第一篇文章。 所以我正在嘗試使用visual python製作模型太陽系。我將每個行星定義爲一個球體,具有半徑,與太陽,質量和動量變量的距離。然後將每個行星(或身體)放入列表結構中。正如你目前所看到的,我有一份[地球,月亮,火星]的名單,因爲我不久將解釋太陽被排除在外。太陽能系統模型Python - 列表操作難度
所以我的問題來了,當我試圖計算每個身體對每個其他身體造成的力量。我在這裏所做的是,對於身體列表中的每一個第i個值,計算它與第n個身體之間的力量,列舉身體中第i個身體的力量是第i個身體與第n個身體之間的力的總和body從0到列表的末尾。 (即列表中所有其他物體的所有力的總和)
這適用於月球和火星(列表中的第二和第三項),但不適用於地球。下面的代碼的輸出是,
<3.57799e+022, 0, 0>
<4.3606e+020, 0, 0>
<1.64681e+021, 0, 0>
<-1.#IND, -1.#IND, -1.#IND> - this is the total force on earth.
<0, 2.07621e+027, 0>
<0, 9.83372e+027, 0>
from visual import *
AU = 149.6e9
MU = 384.4e6 # moon - earth orbital - radius
MarU = 227.92e9
G =6.673e-11
sun_mass =2e30
sun_radius =6.96e8
earth_mass =6e24
earth_radius =6.37e6
moon_mass =7.35e22
moon_radius =1.74e6
mars_mass = 6.41e23
mars_radius = 3390000
sun = sphere (pos =(0 , 0 ,0) , velocity = vector (0 ,0 ,0) ,mass = sun_mass , radius =0.1* AU , color = color . yellow)
earth = sphere (pos =(AU , 0 ,0) ,mass = earth_mass , radius =63170000, color = color . cyan ,make_trail=True)# create a list of gravitating objects
moon = sphere (pos =(AU+MU , 0 ,0) ,mass = moon_mass , radius =17380000 , color = color . white, make_trail=True)
mars = sphere (pos =(MarU , 0 ,0) ,mass = mars_mass , radius = mars_radius , color = color . red, make_trail=True)
#initialise values:
we = 1.9578877e-7
wm = sqrt(G*earth.mass/3.38e8**3)
wma = 9.617e-5
dt = 3*60
earth.mom = vector(0,1.5e11*earth.mass*we,0)
mars.mom = vector(0, 9.833720638948e+27,0)
moon.mom = moon.mass*(earth.mom/earth.mass+vector(0,-3.48e8*wm,0))
bodies = [earth, moon, mars]
*N = 0
initialdiff = 0
for i in bodies:
initialdiff = i.pos - sun.pos
TotalForce = (G * i. mass * sun. mass * norm (initialdiff)/ initialdiff . mag2)
print TotalForce
while N < len(bodies):
if N!=i:
diff = i.pos - bodies[N].pos
Force = (G * i. mass * bodies[N]. mass * norm (diff)/ diff . mag2)
TotalForce = TotalForce + Force
i.mom = i.mom+TotalForce*dt
N = N+1
else:
N = N+1
print earth.mom
print moon.mom
print mars.mom*
感謝您的任何幫助,你可以給。
你能更具體地說明「正確」工作的含義嗎?即。你期待什麼,你的代碼如何偏離你的期望? –
很抱歉。所以有問題的部分是計算列表中每個對象的淨力。矢量列表是代碼的輸出。前三個由於太陽(初始力)正確地顯示列表中每個物體上的力,則接下來的三個矢量顯示總淨力(太陽的力加上由於列表中的其他物體造成的力)然而,地球的矢量輸出不是輸出數字,而我很困惑,什麼#IND actualy意味着什麼。我也很困惑,爲什麼會出現這個結果,我看不到循環結構在哪裏破壞。 – user3788578
-1。#IND是一個特殊的結果,通常意味着零除以零...這是否有可能發生在你的代碼中的某個地方? –