Search code examples
floating-pointdoubleexpressiondnan

what is .nan in D programming language?


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?


Solution

  • 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.