我們假設有一個已知中心(Xo,Yo,Zo)和半徑Ro的大球體。它包含數百萬個相對於同一參考框架具有已知質量和3d位置的粒子。在這個大球體內部,有十幾個隨機分佈在三維空間中的較小虛擬球體,但其他位置已知。我想計算每個較小球體內部的粒子數量,從而計算每個較小球體(容器)的質量,方法是計算每個球體內部的粒子數量。如何將值從最內層的while循環傳遞到python中的outer for循環?
這裏是我的MWE片段,其中我循環遍歷各個粒子,看它們是否在每個較小的球體內,然後爲每個球體單獨計數它們以便爲每個較小的球體計算出總質量:
import numpy as np
from scipy.spatial.distance import euclidean
### there is 10 small spheres inside Big Sphere each containing different number of particles and hence different masses
### small_sphere_id_array is the array of the IDs of the small spheres
### small_sphere_position_array is the array of the position of the center of small spheres
### small_sphere_radius_array is the array of the radii of small spheres
### small_sphere_mass_array is the array of the masses of small spheres
### particle_position_array is the array of the positions of particles inside the Big Sphere
### particle_mass_array is the array of the masses of particles inside the Big Sphere
for small_sphere_index in np.arange(0, 10)):
for particle_index in np.arange(0, 6000000)):
small_sphere_mass_array = []
small_sphere_mass = 0
distances = euclidean(particle_position_array[particle_index], small_sphere_position_array[small_sphere_index])
success_condition = (distances <= small_shpere_radius_array[small_sphere_index])
while success_condition:
small_sphere_mass += particle_mass_array[particle_index]
small_sphere_mass_array.append(small_sphere_mass)
small_sphere_mass = np.sum(small_sphere_mass_array)
else:
break
print('{}, {}'.format(small_sphere_id_array[small_sphere_index], small_sphere_mass))
我期待打印出10行(對應於10個小球體),其ID爲第一個,然後是總質量。但是,這裏是輸出我有:
some number, 0
some number, 0
some number, 0
some number, 0
some number, 0
some number, 0
some number, 0
some number, 0
some number, 0
some number, 0
尤其是我不能接受while
循環的結果,並將其移動到外for
循環,因此對所有的粒子循環拿出一個非零總質量爲每個小球體。我似乎正確地循環了10個小球,但問題是質量最終爲零,這意味着中間的for
循環無法解釋所有6000000個粒子。 (提示:所有的粒子做有腫塊。)
您是否通過打印success_condition檢查了它是否爲True? – Ujjwal
我期望它至少對於上述範圍內的一些* particle_index *值是真實的,但是我在運行代碼時得到全零,這意味着它只通過循環一次(它巧合地產生零),並且已經檢查過那肯定。我無法通過所有值(0,6000000),因此在循環結束時,我將以10 *個小球*中的每一個爲單個值。 – Allan