优化n体引力吸引算法

时间:2016-09-22 00:21:47

标签: java arrays algorithm optimization physics

我正在编写一个2d原行星盘的模拟,而现在,最耗时的代码就是计算引力。这是我目前正在使用的代码。

for(int i=0; i<particleCount; i++){
    if(boolArray[i]){    //boolArray is linked with particleArray, false means the linked particle has collided with another particle and no longer exists
        double iX = particleArray[i].getXPosition();
        double iY = particleArray[i].getYPosition();
        double iM = particleArray[i].getMass();
        for(int j=0; j<particleCount; j++){
            if(i!=j&&boolArray[j]){
                double rX = iX-particleArray[j].getXPosition();
                double rY = iY-particleArray[j].getYPosition();
                double rT = Math.sqrt(rX*rX+rY*rY);
                double rF = rT*rT*rT;
                double fT = -constantGravity*iM*particleArray[j].getMass()/rF;
                particleArray[i].updateForce(rX*fT, rY*fT);
            }
        }
    }
}

有没有人对如何加快它有任何想法?

中的sqrt
double rT = Math.sqrt(rX*rX+rY*rY);

是最大的罪魁祸首,但我不确定我是否能摆脱它。

可以在https://github.com/quietsamurai98/2D-Accretion-Simulation/tree/Trails-png

找到可编译代码

2 个答案:

答案 0 :(得分:1)

您为每对点计算两次。 试试这个。

for (int i = 0; i < particleCount; i++) {
    if (boolArray[i]) { // boolArray is linked with particleArray, false
                        // means the linked particle has collided with
                        // another particle and no longer exists
        double iX = particleArray[i].getXPosition();
        double iY = particleArray[i].getYPosition();
        double iM = particleArray[i].getMass();
        for (int j = i + 1; j < particleCount; j++) {
            if (boolArray[j]) {
                double rX = iX - particleArray[j].getXPosition();
                double rY = iY - particleArray[j].getYPosition();
                double rT = Math.sqrt(rX * rX + rY * rY);
                double rF = rT * rT * rT;
                double fT = -constantGravity * iM * particleArray[j].getMass() / rF;
                particleArray[i].updateForce(rX * fT, rY * fT);
                particleArray[j].updateForce(-rX * fT, -rY * fT);
            }
        }
    }
}

答案 1 :(得分:0)

您也可以使用四叉树(或三维树)。然后计算同一单元内每个物体的重力,然后对每个外部单元计算单元内质量的总和,并用该质量计算该单元中心的重力。这将失去精确度,但是具有良好平衡的四叉树,并且非常大量的N体看起来非常逼真。 https://en.wikipedia.org/wiki/Barnes%E2%80%93Hut_simulation

相关问题