我正在做一个简单的n体仿真。现在,我要对其进行“强制执行”,这意味着我要计算每帧每个对象在每个其他对象上施加的所有力。我现在的问题是,如果我选择大量的对象(例如2000),在某些情况下,刚开始时对象“行星”会消失约2帧。当我通过添加System.out.println(PlanetHandler.planets.get(0).position.x);到主循环中检查发生了什么时,我得到487.0486.99454NaNNaN通过注释一些东西和反复试验,我发现问题出在这里: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>。我已经花了很长时间了,但是还没有弄清楚是什么导致值(位置,速度)过大。也许有一定经验的人或者通常精通这种事情的人可以帮助我。
1 回答
![?](http://img1.sycdn.imooc.com/54584f850001c0bc02200220-100-100.jpg)
12345678_0001
TA贡献1802条经验 获得超5个赞
这是JVM给您NAN的典型情况。您遇到的是零除以零(0/0),这在数学中是不确定的形式。
如果 float dist = Vector2Math.distance(planet.position, otherPlanet.position);
返回0。
下一条语句
float force = Constants.GRAVITATIONAL_CONSTANT * ((planet.mass*otherPlanet.mass)/(dist*dist));
计算力时,力除以零。
另外,我建议您在需要精度时使用BigDecimal。您也可以在这里参考答案之一
添加回答
举报
0/150
提交
取消