我正在编写 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/