Why is this expression returning NaN?

353 Views Asked by At

For smoother ship movement, I am going to gradually move it to it's actual location - So like this:

(mz - sz) / (10 * (60 / TerrainDemo.FPS))

mz is the ship's actual location on the Z axis - And I divide it by 10, and obviously at the end I account for the FPS.

However, on seemingly random occasions, this is returning NaN.

How can I fix this to not return NaN?

2

There are 2 best solutions below

2
On BEST ANSWER

This expression gives NaN in each one of the following cases:

 mz type | sz type | FPS type | Condition
---------|---------|----------|-----------------------------------------
 int     | int     | float    | (FPS == inf || FPS == -inf) && mz == sz
---------|---------|----------|-----------------------------------------
 int     | float   | int      | (FPS  >  60 || FPS  <  -60) && mz == sz
---------|---------|----------|-----------------------------------------
 float   | int     | int      | (FPS  >  60 || FPS  <  -60) && mz == sz

In addition to that, if the value of any of these variables is NaN to begin with, then so will be the value of the entire expression.

1
On

In many scripting programming languages, when a variable or atrribute of object has not been declared, it is "undefined". So an arithmetic operation is NaN (Not a Number) when a variable is undefined, null or incompatible type with number operation.

So I think in some "moment" mz, sz or TerrainDemo.FPS cause a invalid operation.

The solution is find which variable is NaN and set a default value for this situation (maybe using conditionals or return 0 when your operation is NaN).

P.S.: Some language, like Javascript, have the special values NaN and Infinity. So

  • Infinity + -> Infinity
  • Infinity - Infinity -> NaN
  • Number / 0 -> Infinity (anothers raise an exception)
  • Number / Infinity -> 0

To see all indeterminate forms go here.