Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java重力环优化_Java_Loops - Fatal编程技术网

Java重力环优化

Java重力环优化,java,loops,Java,Loops,为什么在第二个环上,天体似乎破碎了,例如,我试图优化我的行星系统,以支持更多的天体 for(Body body : bodies){ PVector totalForce = new PVector(); for(Body other : bodies){ if(body != other){ PVector fxy = body.attraction(other); totalForce.x += fxy.x;

为什么在第二个环上,天体似乎破碎了,例如,我试图优化我的行星系统,以支持更多的天体

for(Body body : bodies){
    PVector totalForce = new PVector();
    for(Body other : bodies){
        if(body != other){
            PVector fxy = body.attraction(other);
            totalForce.x += fxy.x;
            totalForce.y += fxy.y;
        }
    }

    body.vel.x += totalForce.x / body.mass * timestep;
    body.vel.y += totalForce.y / body.mass * timestep;
    body.pos.x += body.vel.x * timestep;
    body.pos.y += body.vel.y * timestep;
}
第二个循环,其中只有一个物体在移动,而它在错误的方向上移动

PVector totalForce = new PVector();
PVector fxy = new PVector();
for(int i = 0; i + 1 < bodies.size(); i++){
    Body body = bodies.get(i);
    Body other = bodies.get(i + 1);
    System.out.println(body + " " + other);
    fxy = body.attraction(other);
    totalForce.x += fxy.x;
    totalForce.y += fxy.y;
    body.vel.x += totalForce.x / body.mass * timestep;
    body.vel.y += totalForce.y / body.mass * timestep;
    body.pos.x += body.vel.x * timestep;
    body.pos.y += body.vel.y * timestep;
}
PVector totalForce=new PVector();
PVector fxy=新的PVector();
对于(inti=0;i+1

代码似乎没有施加影响身体的所有力

Body body = bodies.get(i);
Body other = bodies.get(i + 1);
这两条线是可疑的,必须仔细考虑

数学上,可能会帮助您优化

因此,一个可能的候选人是:

n=num_of_bodies;
for(int i=0;i<n-1;++i)
{
    for(int j=i+1;j<n;++j)
    {
        final Body body=bodies.get(i);
        final Body other=bodies.get(j);
        PVector fxy = body.attraction(other);
        float c=timestep/body.mass;
        body.vel.x+=fxy.x*c;
        body.vel.y+=fxy.y*c;

        c=-timestep/other.mass;
        other.vel.x+=fxy.x*c;
        other.vel.y+=fxy.y*c;

    }
}
for(Body body:bodies)
{
    body.pos.x+=body.vel.x*timestep;
    body.pos.y+=body.vel.y*timestep;
}
n=实体的数量;

对于(inti=0;i,在您的第一个样本中,您正在检查每一对可能的身体

a、 b,c-(a,b)、(a,c)、(b,c)

在第二个示例中,您正在检查每个相邻的实体

a、 b,c-(a,b)、(b,c)


对于初学者,我会在PVector中实现向量加法来分离代码。现在每行代码都要写两次。那么,您成功优化了代码了吗?