java - 优化 n 体引力吸引算法

标签 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 找到编译就绪的代码

最佳答案

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

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);
            }
        }
    }
}

关于java - 优化 n 体引力吸引算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39628393/

相关文章:

java - Hibernate只选择一些字段并映射到Map

java - struts2的迭代器标签

java - 无法扩展 GCMIntentService 来修改 native Android 客户端的通知 View [Worklight 7.0 + Android]

c - 如何在文本文件中使用strtok

java - 将 CSV 文件转换为 2D 数组 Java

c - 数组的所有元素都被覆盖而不是仅一个元素?

algorithm - 在不使用字典的情况下识别拼写错误的算法是什么?

java - 如何在 Java 中加速读写 base64 编码的 gzip 大文件

r - 如何在迷宫中找到最短路线?

algorithm - 有没有一种有效的方法来计算节点图上的热图之类的东西?