0

I've been having problems with my code for two weeks, and have been unsuccessful in debugging it. I've come here in the hope that someone can help. I've written a program that utilizes the Barnes-Hut algorithm for n-body gravitational simulation. My problem is that one or more 'particles' will have the position of {NaN, NaN, NaN} assigned to them (using three doubles to represent x, y, z of 3-d space). This, in turn, causes the other particles to have an acceleration of {NaN, NaN, NaN}, and in turn, a velocity and position of {NaN, NaN, NaN} as well. Basically, after a frame or two, everything disappears. It seems to be occurring in the updateAcc method, but I have a feeling that this isn't so. I understand that this is a huge undertaking, and am very grateful for anyone that helps me. What I've checked: There are no negative square roots, and all the values seem to be within their limits. The source code is available here. Thanks again.

Code that seems to produce NaN:

private static void getAcc(particle particle, node node)
{
    if ((node.particle == null && node.children == null) || node.particle == particle)
    {
        //Geting gravity to a node that is either empty or the same node...
    }
    else if (distance(node.centerOfMass, particle.position) / node.sideLength > theta && node.children != null)
    {
        for (int i = 0; i < node.children.length; i++)
        {
            if (node.children[i] != null)
            {
                getAcc(particle, node.children[i]);
            }
        }
    }
    else
    {
        particle.acceleration = vecAdd(particle.acceleration, vecDiv(getForce(particle.position, particle.mass, node.centerOfMass, node.containedMass), particle.mass));
    }
}
private static double sumDeltaSquare(double[] pos1, double[] pos2)
{
    return Math.pow(pos1[0]-pos2[0],2)+Math.pow(pos1[1]-pos2[1],2)+Math.pow(pos1[2]-pos2[2],2);
}
private static double[] getForce(double[] pos1, double m1, double[] pos2, double m2)
{
    double ratio = G*m1*m2;
    ratio /= sumDeltaSquare(pos1, pos2);
    ratio /= Math.sqrt(sumDeltaSquare(pos1,pos2));
    return vecMul(vecSub(pos2, pos1), ratio);
}
private static double distance(double[] position, double[] center)
{
    double distance = Math.sqrt(Math.pow(position[0]-center[0],2) + Math.pow(position[1]-center[1],2) + Math.pow(position[2]-center[2],2));
    return distance;
}
9
  • 1
    When the first particle is assigned the {NaN NaN NaN} coordinates, where do those coordinates originate from? That piece of code would be a good idea to post.
    – Hidde
    Commented Mar 14, 2012 at 23:17
  • That's just it - I haven't been able to locate where the NaN actually comes from. Commented Mar 14, 2012 at 23:21
  • 5
    Vote to close: Asking strangers to spot errors in 100s of lines of your code by inspection is not productive. You should use the debugger (or lots of print statements) to trace backwards; there must be a calculation somewhere that's producing NaN. Commented Mar 14, 2012 at 23:21
  • @danfoster When you print the coordinates just before they are assigned to the particle, are they a number or NaN? If they are NaN, check where that variable got its value from. Keep doing that, until you find a piece of code that doesnt do what you want it to do. Post that piece of code, so that we can help you.
    – Hidde
    Commented Mar 14, 2012 at 23:24
  • Give me a minute. Posted what Seems to be giving me trouble. Sorry for the long post. Commented Mar 14, 2012 at 23:32

3 Answers 3

1

I'm not sure if this is the only problem, but it is a start.

sumDeltaSquare will sometimes return 0 which means when the value is used in getForce ratio /= sumDeltaSquare(pos1, pos2); it will produce Infinity and start causing issues.

This is a serious problem that you need to debug and work out what everything means. I enjoyed looking at the dots though.

1
  • Only when two different masses occupy a single position. I'm not sure how often this should happen in a gravitational simulator, unless you're trying to go inside a singularity. In this case, the NaN would definitely indicate a much more important error. Commented Mar 16, 2012 at 23:37
1

Firstly, why aren't you using Java's Vecmath library? (It's distributed as a part of Java3D. Download Java3D's binary build and then just use vecmath.jar) Your problem is, very likely, somewhere in your custom vector functions. If not, @pimaster is probably right in that your translation magnitude method sumDeltaSquare might be returning 0 if two of your masses occupy a single space. Which means, unless you're inside a black hole, you're doing it wrong :P. Or you need to come up with a quantum gravity theory before you can do this simulation.

If you can't use vecmath (i.e. this is a homework assignment) I would suggest you use a regex to find every instance of return * and then replace it with assert !Double.isNan(*) && Double.isFinite(*);\nreturn *, except substitute * for whatever regex finds a "match group". I've forgotten exactly what that is, but I got you started on Google. I also suggest you avoid optimizations until after you have working code.

1
  • That assert will always pass because Double.NaN != Double.NaN. Use assert ! Double.isNaN(...); instead Commented Dec 10, 2014 at 20:11
0

I'm not going to debug your code. But NaN values are the result of mathematically invalid operations on floating point numbers. The most famous of those is division by 0 (does not throw an exception with floating point). How can this happen?

If your computation produces very small numbers, they might become too small to be represented as 64-bit floating point numbers (they require more bits than are available), and Java will return 0.0 instead. In the other direction, if you get an overflow (the magnitude of the number requires too many bits), Java turns this into infinity. Doing math with infinity and 0 can quickly lead to NaN, and NaN propagates through every operation you apply to it.

For details, see sections 4.2 and 15.17 of the Java language spec.

3
  • Division by 0 does not, in general, cause a NaN. Commented Mar 15, 2012 at 0:22
  • With Java float, a division by zero results in Float.NEGATIVE_INFINITY or Float.POSITIVE_INFINITY, depending on the sign of the numerator.
    – Mike Clark
    Commented Mar 15, 2012 at 0:40
  • True. I read the spec a little too fast. Division by 0 only returns NaN when when you do 0.0/0.0. Nonetheless, I think producing NaNs through computation is exactly what the problem with the above code is.
    – Jochen
    Commented Mar 15, 2012 at 1:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.