Causes for NaN in C++ application that do no raise a floating point exception
Asked Answered
J

2

11

To find the cause of floating point variables beeing set to NaN in my C++ program I enabled floating point exceptions like this:

#include <fenv.h>
feenableexcept(FE_INVALID | FE_OVERFLOW);

I know it works because when I write:

int val = 0.0/0.0;

in my program a floating point exception is risen. But NaNs are "spreading" through the floating point calculations of my program and I have no idea which variable is set to NaN first.

What causes for a variable beeing set to NaN exist, that would not cause a floating point exception?

Jaunitajaunt answered 22/3, 2011 at 16:19 Comment(10)
When adding FE_UNDERFLOW I get lots of exceptions where I am multiplying by 0. Can an underflow really cause a NaN?Jaunitajaunt
@Jaunitajaunt Are you sure you aren't actually multiplying by a very small number close to zero?Coif
@Nathan: As far as I read it, yes. Have a look at en.wikipedia.org/wiki/IEEE_754-2008Mope
@Nathan: An alternate way of tracking this down would be to make an isNaN function and start littering your code with assert(!isNaN(x))Mope
@Jaunitajaunt @Mope Just to be explicit, here's how you can write isNaN: template<typename T> bool isNaN(T value) { return value != value; }Garlandgarlanda
@Erik. Looking on link the only thing about underflow is this: a result is very small (outside the normal range) and is inexact. That does not cause a NaN, does it? Am I missing something?Jaunitajaunt
@Erik, @SuperEletric Yes, littering with isNaN tests is a possibility. That's what I am doing so far. It is very annoying that is why I am searching for an alternative.Jaunitajaunt
@Nathan: IIRC there's a FE_ALL flag, doubt it'd help much if you get exceptions for underflow already though.Mope
Underflow cannot generate a NaN.Tessler
Underflows and overflows can, however, generate infs and 0s, which can quickly lead to NaNs.Neigh
T
7

If any input has a quiet NaN value, it will cause the result of nearly any floating-point operation that consumes it to be NaN without raising the invalid exception.

The most likely explanation is that some data is being read from the wrong address, and that the read data (which may not even be floating-point data) happens to match a quiet NaN encoding. This can happen pretty easily, because the relatively common pattern 0xffff... encodes a quiet NaN.

Tessler answered 28/12, 2012 at 16:59 Comment(0)
O
2

Are you doing any square root operation? If you try to compute a square root for a negative number as in sqrt(-1) then you will get a Nan. In this case you should get an 'Invalid Operation' exception though. Are you sure you are trapping correctly all exceptions? It seems like a numeric exception is untrapped somewhere in your code.

Oblation answered 25/3, 2011 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.