Under Review
over 1 year ago

Testing for NaN do not work when returned from a Math function

See this thread:

https://forums.garmin.com/developer/connect-iq/f/discussion/338071/testing-for-nan/1637852#1637852

The following code snippet works

var rad = NaN;
System.println("rad == NaN: " + (rad == NaN)); // false
System.println("rad.equals(NaN): " + rad.equals(NaN)); // true

It returns

rad == NaN:false

rad.equals(NaN): true

The following code snippet does NOT work

var rad = Math.acos(45);
System.println("rad == NaN: " + (rad == NaN)); // false
System.println("rad.equals(NaN): " + rad.equals(NaN)); // true

It returns

rad == NaN:false

rad.equals(NaN): false

In both cases, rad is NaN (Lang.Float) but in the bottom one, both line returns 'false'. How can one check for NaN returned from a Math function???

Running CIQ 4.2.4.

  • For further context it seems that Math.acos(45) actually returns -NaN (rendered as "-nan(ind)" by System.println), but:

    - there's no constant for -NaN

    - typing "-NaN" doesn't work because any mathematical operation on NaN just yields NaN again

    - there's no isFinite() function in Monkey C

    As noted in the linked thread, the workaround is to write a utility function such as:

    public function isFinite(x as Number or Long or Float or Double) as Boolean {
      return !x.equals(NaN) && !x.equals(Math.acos(45));
    }

    This seems kind of ridiculous to me.