3

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?

SAL
  • 1,218
  • 1
  • 14
  • 34

1 Answers1

2

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.

  • 1
    -finit-real=nan is very useful and will save me some lines of code. – SAL Jan 29 '18 at 12:48
  • 2
    So can I safely use NaN to effectively shortcut error checking (ie any calc involving a NaN will result in a NaN therefore I don't need to check before I try the calc)? Or will this blow up on me in some way that I don't understand?! – SAL Jan 29 '18 at 12:51
  • 2
    It really depends on the calculation itself. If you mean simple arithmetic as you showed, then mostly yes. And also depends what you mean by "error checking". There are many types of errors. I personally find valgrind and sanitizations more helpful. But initializing arrays to nonsensical values can give you an early warning which can be very helpful. – Vladimir F Героям слава Jan 29 '18 at 12:54