1

I really can't understand why this expression gives me a NaN error only when

acceleration.module - Ambient.friction = 0

:

double x = (speed.module * speed.direction.x()) + ((acceleration.module-Ambient.friction) * acceleration.direction.x())*time;

Moreover if I add pharentesis like these:

double x = ((speed.module * speed.direction.x()) + ((acceleration.module-Ambient.friction) * acceleration.direction.x()))*time;

it gives me a NaN error again.

Lapo
  • 882
  • 1
  • 12
  • 28

2 Answers2

0

In the first, the second value is multipled by time.

double x = (speed.module * speed.direction.x()) + ((acceleration.module-Ambient.friction) * acceleration.direction.x())*time;

For the other, the whole thing is multiplied by time:

double x = ((speed.module * speed.direction.x()) + ((acceleration.module-Ambient.friction) * acceleration.direction.x()))*time;

This makes me think you are overflowing the double values in the second one before you multiple with time. With double overflow you get the magic values Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY

Most likely you are multiplting time with Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY and the result is NAN.

Change the calculations to a series of steps. With each step, check the result for overflow, by looking for Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY. That will tell you where things go off the rails. You are almost certainly overflowing somewhere, but we cannot see the numbers you are handling so I cannot tell you exactly where.

Sean F
  • 4,344
  • 16
  • 30
  • Thank you for the answer. I'm building this program with OpenGL ES for Android and I noticed that sometimes the time elapsed between 2 frames is evaluated 0.0 (I don't know why, I'll check later). For this reason when this happens I get a -0.0 value that create the problem (I think). – Lapo Mar 27 '18 at 16:41
  • Yes, you should check for that number too, once you have that number maybe you cannot multiply or add to it either or maybe it ends up giving you NAN as well: https://stackoverflow.com/questions/6724031/how-can-a-primitive-float-value-be-0-0-what-does-that-mean Sometimes for issues like this rearranging the order of calculations can avoid the issue. – Sean F Mar 27 '18 at 16:47
  • Once you have the series of individual steps, this reference can be used as a reference http://www.programgo.com/article/4441958781/ to see how you end with NAN – Sean F Mar 27 '18 at 16:52
0

My (educated) guess is the nan is already in the direction because it will be indeterminate when module is zero

Paul Janssens
  • 622
  • 3
  • 9