In another question, it was found that dividing zero by a variable containing a real zero results in a value of -nan .

 #include <iostream> int main() { double zero = 0; std::cout << 0/zero << "\n"; } 

The result is the same for the main most popular compilers:

Is there any practical sense in this minus, why not just nan ?

  • And why +0/-0 in JS? - user207618
  • @Aid with zero can be explained by the desire from one side or the other. Here the original arguments are not negative. - αλεχολυτ
  • I would put on optimization. ideone.com/U1QxkB here is a little clearer (or not ...) - pavel
  • @pavel want to say that just calculations lead to the installation of a sign bit, but to remove it is an unnecessary action, so is there a minus? - αλεχολυτ
  • one
    There is an answer. - ixSci

1 answer 1

It turns out that all the above mentioned examples were run on the x86 architecture, and for FPU it has the following rule:

When it comes to the operation of a floating-point operation, it is a rule (see Tables 8-10 and 11-1), the result is commonly known as the QNaN FP Indefinite (Section 4.8.3.7).

Taken from Intel® 64 and IA-32 Architectures Software Developer's Manual Volume 1: Basic Architecture Section 4.8.3.5.

Looking at the table specified in the quote above, we find there the following operation, which gives the output QNaN:

Division: ∞ by ∞; 0 by 0.

Those. just what we have in question (there are other operations there). And if we look at table 4-3, from section 4.2.2, we see that in QNaN the sign bit is set to 1, which explains the appearance of negative NaN in the output.


And if you look at it all from the point of view of language, you get an indefinite behavior, so we can see anything.

C ++ 14, [expr] p4:

It is not clear.


The answer is inspired by a wonderful post from Raymond Chen.

  • It is necessary to check on the ARM or something. Find where only. And something is not very clear what is the difference QNaN Floating-Point Indefinite and just QNaN . - αλεχολυτ
  • @alexolut, the differences are that these two NaNs are obtained differently, look at table 8-10 (by searching pdf Table 8-10), it says under what circumstances it turns out just QNaN, and under which QNaN Ind - ixSci
  • Yes, only this definition from the standard is unclear. The division of 0 by 0 mathematically defined in IEEE 756 is NaN. In this case, the Standard is intentionally vague. - SergeyA
  • @SergeyA, well, yes, the standard does not define what “mathematically defined” generally means, so here you can fantasize anything. - ixSci