几帧后对象变量变为NaN

我正在做一个简单的n体仿真。现在,我要对其进行“强制执行”,这意味着我要计算每帧每个对象在每个其他对象上施加的所有力。


我现在的问题是,如果我选择大量的对象(例如2000),在某些情况下,刚开始时对象“行星”会消失约2帧。当我通过添加System.out.println(PlanetHandler.planets.get(0).position.x);到主循环中检查发生了什么时,我得到


487.0

486.99454

NaN

NaN

通过注释一些东西和反复试验,我发现问题出在这里:


private static void computeAndSetPullForce(Planet planet)

{

    for(Planet otherPlanet : planets)

    {

        //Also here, if we are deleting the planet, don't interact with it.

        if(otherPlanet != planet && !otherPlanet.delete)

        {

            //First we get the x,y and magnitudal distance between the two bodies.

            int xDist = (int) (otherPlanet.position.x - planet.position.x);

            int yDist = (int) (otherPlanet.position.y - planet.position.y);

            float dist = Vector2Math.distance(planet.position, otherPlanet.position);


            //Now we compute first the total and then the component forces

            //Depending on choice, use r or r^2

            float force = Constants.GRAVITATIONAL_CONSTANT * ((planet.mass*otherPlanet.mass)/(dist*dist)); 

            float forceX = force * xDist/dist;

            float forceY = force * yDist/dist;


            //Given the component forces, we construct the force vector and apply it to the body.

            Vector2 forceVec = new Vector2(forceX, forceY);

            planet.force = Vector2Math.add(planet.force, forceVec);

        }

    }

}

“行星”列表是CopyOnWriteArray<Planets>。我已经花了很长时间了,但是还没有弄清楚是什么导致值(位置,速度)过大。也许有一定经验的人或者通常精通这种事情的人可以帮助我。


至尊宝的传说
浏览 175回答 1
1回答

12345678_0001

这是JVM给您NAN的典型情况。您遇到的是零除以零(0/0),这在数学中是不确定的形式。如果&nbsp;float dist = Vector2Math.distance(planet.position, otherPlanet.position);返回0。下一条语句float&nbsp;force&nbsp;=&nbsp;Constants.GRAVITATIONAL_CONSTANT&nbsp;*&nbsp;((planet.mass*otherPlanet.mass)/(dist*dist));计算力时,力除以零。另外,我建议您在需要精度时使用BigDecimal。您也可以在这里参考答案之一
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java