![](/img/trans.png)
[英]Any way to dynamically insert linebreaks depending on the length of the string?
[英]Is there a way to dynamically change variables depending on length of list
可能看起來像一個愚蠢的問題是有什么方法可以根據列表中的對象數量創建變量。 這方面的背景是我正在嘗試創建一個 n 身體模擬。 一種用戶可以在太陽系中手動選擇他們想要的行星,然后僅使用這些行星運行腳本的一種方式。 所以在他們運行選擇行星和運行腳本之前,我不知道要創建多少變量。 這個要創建多少變量的問題通過以下方式顯示: 質量由 class 對象創建: class 對象():
position = np.full((1, 3), 0)
velocity = np.full((1, 3), 0)
acceleration = np.full((1, 3), 0)
name = ""
mass = np.full((1, 1), 0)
planets_init = np.full((1, 3), 0)
def __init__(self, Name, Mass, initPosition, initVelocity, initAcceleration):
au = 149597870.700e3
v_factor = 1731460
self.name = Name
self.mass = Mass
function 通過使用 scipy.integrate.solve_ivp 解決:
three_body_sol = sci.integrate.solve_ivp(fun=Objects.ThreeBodyEquations,t_span=domain,y0=init_params,args=(G,planets_mass,N), max_step=max_step)
其中 function 是:
def ThreeBodyEquations(t,w,G,mass,N):
# N being the number of objects in the system so in this case 2
m1, m2 = mass
#Unpack all the variables from the array "w"
r1=w[:3]
r2=w[3:6]
v1=w[6:9]
v2=w[9:12]
# Harry's attempt
G = G
planets_pos = np.vstack((r1, r2))
planets_mass = mass # np.vstack((m1, m2))
# positions r = [x,y,z] for all particles
x = planets_pos[:,0:1]
y = planets_pos[:,1:2]
z = planets_pos[:,2:3]
# matrix that stores all pairwise particle separations: r_j - r_i
dx = x.T - x
dy = y.T - y
dz = z.T - z
# matrix that stores 1/r^3 for all particle pairwise particle separations
inv_r3 = (dx**2 + dy**2 + dz**2)
inv_r3[inv_r3>0] = inv_r3[inv_r3>0]**(-1.5)
ax = G * (dx * inv_r3) @ planets_mass
ay = G * (dy * inv_r3) @ planets_mass
az = G * (dz * inv_r3) @ planets_mass
# planets_acceleration = np.sqrt(ax**2 + ay**2 + az**2)
planets_acceleration = np.vstack((ax,ay,az))
planets_acceleration = planets_acceleration.flatten()
dv1bydt=planets_acceleration[0::N]
dv2bydt=planets_acceleration[1::N]
# print(planets_acceleration)
dr1bydt=v1
dr2bydt=v2
#Package the derivatives into one final size-18 array
r12_derivs=np.concatenate((dr1bydt,dr2bydt))
r_derivs = r12derivs
v12_derivs=np.concatenate((dv1bydt,dv2bydt))
v_derivs= v12_derivs
derivs=np.concatenate((r_derivs,v_derivs))
return derivs
我的主要問題圍繞着這個 function。 當用戶定義他們想要使用的行星時,我不知道行星的數量是多少。 我知道可能的范圍,但僅此而已。 有沒有可行的方法來做到這一點,或者這是一個失敗的原因?
我希望這可以通過一些額外的代碼來澄清這個問題。 抱歉之前缺少代碼,一開始我沒有意識到它很有價值,也不想負擔太多代碼。
我將創建一個首先計算質量的 function,例如
mass = 0
for planet in planet_list:
mass = mass+ planet.mass
return mass
total_mass = calculate_combined_mass([earth, Mars, jupiter] )
three_body_equations(t,w,G,total_mass,N)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.