我已經在python中創建了一個粒子的小型可視化。 我是在零重力的二維空間中粒子的運動。由於每個粒子都基於粒子質量和距離吸引所有其他粒子。在零重力二維空間中優化粒子的引力計算
我在pygame中做了一個可視化,並且所有工作都按照計劃進行(有了計算),但是我需要優化計算extreamly。今天,該系統可以計算大約100-150個顆粒的相鄰幀率。我把所有的計算都放在一個單獨的線程中,給了我更多但並不是我想要的東西。
我看着scipy和numpy,但因爲我不是科學家或mathguru我只是感到困惑。它看起來像我在正確的軌道上,但我不知道如何。
我需要計算所有粒子上的所有吸引力,我必須在一個循環中循環。 因爲我需要找到是否有任何碰撞,我必須再一次做同樣的事情。
它打破了我的心臟寫那種代碼....
numpy的具有計算與陣列陣列的能力,但是我還沒有發現任何東西來計算所有的項目在數組中的所有項目來自同一個/另一個陣列。有一個嗎? 如果是這樣我可以創建和對數組和計算速度更快,而且必須是從2個陣列,其中它們的值匹配(Collitiondetect IOW)
下面是今天的吸引/ collsion計算得到指數函數:
class Particle:
def __init__(self):
self.x = random.randint(10,790)
self.y = random.randint(10,590)
self.speedx = 0.0
self.speedy = 0.0
self.mass = 4
#Attraction
for p in Particles:
for p2 in Particles:
if p != p2:
xdiff = P.x - P2.x
ydiff = P.y - P2.y
dist = math.sqrt((xdiff**2)+(ydiff**2))
force = 0.125*(p.mass*p2.mass)/(dist**2)
acceleration = force/p.mass
xc = xdiff/dist
yc = ydiff/dist
P.speedx -= acceleration * xc
P.speedy -= acceleration * yc
for p in Particles:
p.x += p.speedx
p.y += p.speedy
#Collision
for P in Particles:
for P2 in Particles:
if p != P2:
Distance = math.sqrt( ((p.x-P2.x)**2) + ((p.y-P2.y)**2) )
if Distance < (p.radius+P2.radius):
p.speedx = ((p.mass*p.speedx)+(P2.mass*P2.speedx))/(p.mass+P2.mass)
p.speedy = ((p.mass*p.speedy)+(P2.mass*P2.speedy))/(p.mass+P2.mass)
p.x = ((p.mass*p.x)+(P2.mass*P2.x))/(p.mass+P2.mass)
p.y = ((p.mass*p.y)+(P2.mass*P2.y))/(p.mass+P2.mass)
p.mass += P2.mass
p.radius = math.sqrt(p.mass)
Particles.remove(P2)
你考慮過[Psyco](http://psyco.sourceforge.net/)還是[編寫C/C++模塊](http://docs.python.org/extending/extending.html)? – nagisa
本文回顧了優化重力模擬的常用方法,包括Barnes-Hut。專業人士通常在3D中做,但我相信2D案例都是類似的。 http://www.cs.hut.fi/~ctl/NBody.pdf –
如果你對數學不滿意(「我不是科學家或mathguru我只是困惑」),那麼我認爲你需要尋找這是一個圖書館。見http://stackoverflow.com/questions/6381137/python-physics-library http://stackoverflow.com/questions/2298517/are-any-of-these-quad-tree-libraries-any-good –