Search code examples
fortranieee-754

Deliberately using NaN in Fortran


I've read the informative posts on NaN use in Fortran comparisons (here and here) and I think I've got a handle on roughly what's going on.

My question is more about NaN use in general.

Say I have a collection of reals and I don't know, yet, what their values are. So I set them all to be NaN and, effectively, I use NaN to mean, in part, 'unallocated'. There seems to be some debate as to whether this is a good idea and I've read recommendations to use huge(1.0) or some other 'magic number' instead.

But using NaN seems to have real benefits in that that any calculation involving any variable of value NaN will result in a NaN. Which is helpful (and probably 'correct' in a mathematical sense).

For example if x is set to NaN, and y is 1.23 then

z = x + y
z = x - y
z = x * y
z = x / y

will always result in z being NaN (at least it does with Intel v18 on Windows) - which is what I want: z is unknown because x is unknown.

So - is this an acceptable use of NaN? Or am I creating problems that I'm not aware of yet?


Solution

  • You can do that automatically in many compilers with switches like -finit-real. It can be useful, that's why they supply this switch. Many compilers offer this.

    Note that there are two kinds of NaN. A quiet NaN and a signalling NaN. Usage of he signalling NaN will trigger a floating point exception.

    Whether it to preferred over a different sentinel value is pretty much just an opinion, so I will not answer that, opinion based questions and polls are off-topic here. We cannot really continue here in the debate you linked (Is it a good idea to use IEEE754 floating point NaN for values which are not set?). I don't think it is a good SO question in today's standards (notice how old it is!), and many of those answers wouldn't stand today, but if anyone has something more to add, they can do that in that question, no point raising it here.