-2

From the D programming tutorial:

We have already seen that this is the default value of floating point variables. .nan may appear as a result of meaningless floating point expressions as well. For example the floating point expressions in the following program all produce double.nan:

import std.stdio;

void main()
{
    double zero = 0;
    double infinity = double.infinity;

    writeln("any expression with nan: ", double.nan + 1);
    writeln("zero / zero            : ", zero / zero);
    writeln("zero * infinity        : ", zero * infinity);
    writeln("infinity / infinity    : ", infinity / infinity);
    writeln("infinity - infinity    : ", infinity - infinity);
}

But what is double.nan exactly? Surely it must be some kind of number? Doesn't this necessarily lead to conflict?

Arnab Nandy
  • 6,472
  • 5
  • 44
  • 50
qed
  • 22,298
  • 21
  • 125
  • 196

1 Answers1

2

nan means "not a number", it is basically an error indicator in floating point operations. Any math with nan results in nan because anything else would be meaningless. That's why nan+1 == nan. Dividing by zero yields nan because nothing else makes sense.

Adam D. Ruppe
  • 25,382
  • 4
  • 41
  • 60
  • My question is, despite the name, nan is still represented by a number internally, i.e. (according to wikipedia) s111 1111 1axx xxxx xxxx xxxx xxxx xxxx. So, if nan is represented by this number, how do you do if you want to use this number itself? – qed Sep 13 '14 at 21:37
  • 2
    Oh, I see what you mean now. Yes, there is a bit sequence that represents nan, but it doesn't conflict with normal usage (though note that floating point values are imprecise). The other bits in a double represent the sign, the exponent, and the value. So, conceptually, storing the number 15300 is packed in as more like 1.53 x 10^4, with the 1.53 and the 4 being packed in those xxxx bits. The precision I mentioned does mean not all exact values representable by a 64 bit integer can be represented in a double - indeed some bits are used to signal things like nan - but rounding hides this mostly – Adam D. Ruppe Sep 13 '14 at 21:46
  • ok, got your point. The representation of the number system is sparse in computers. Thanks! – qed Sep 13 '14 at 22:31