3

I found the following from SoloLearn:

I found that 0.0/0.0 makes negative nan(-nan). It makes sense to me that such a mathematical result is undefined, or "not a number". [...]

Furthermore, why is -nan+2^nan=nan?

For example:

#include <iostream>
using namespace std;

int main() {
    cout<<0.0/0.0<<endl;
    cout<<"important "+to_string(1.0/0.0)+"o:"<<endl;
    cout<<"ba"+to_string(0.0/0.0*-1)+"a"<<endl;
    cout<<(0.0/0.0)+2^(0.0/0.0*-1);//-nan+2^nan=nan
    return 0;
}

But this doesn't suffice my logic..

  • 1
    clang and gcc differ live: https://godbolt.org/z/vc37qG – Richard Critten Feb 20 '21 at 19:49
  • 2
    I have found an exact copy from 2020 to this question in another forum: https://www.sololearn.com/Discuss/2152517/why-0-0-0-0-makes-negative-nan-in-c/. I suppose you have read it if you have copied part of the text. Then, what does that question does not answer that you want to know? If you just want to add it to SO you may use the option to answer your own question. – Gary Strivin' Feb 20 '21 at 19:50
  • 2
    Asking a question that was not asked here is fine. But plagiarism is not. If you copy and past a question you should link its source. And not only due to plagiarism but also because there are already answers on that site. – t.niese Feb 20 '21 at 19:54
  • 1
    +ve vs -ve NaNs https://stackoverflow.com/questions/21349847/positive-vs-negative-nans _"...So your platform's conversion functions may print the "sign" of NaN values, but it has no meaning, and you shouldn't consider it for the purposes of testing...."_ – Richard Critten Feb 20 '21 at 19:56
  • What is intended by "accomply" (it's not-a-word)? "Comply"? "Accomplish"? Nothing I've tried substituting seems to fit. Do you simply mean that your results do not match those from the linked and quoted question? (If so, you should add your results to your question.) – JaMiT Feb 20 '21 at 21:12

1 Answers1

5

As far as the C++ language is concerned, the behaviour of the program is undefined. So, from C++ perspective there is no "reason" for anything about the behaviour of the program.

According to the IEEE-754 floating point standard, assuming your hardware and language implementation conform to it (they probably do), result of such division is NaN. IEEE-754 does not specify the sign of NaN for any operation. So from IEEE-754's perspective, the answer is: It just happened to be so on your system for whatever reason the language / hardware implementation has chosen (or simply for no particular reason).

In conclusion: You should never rely on sign of NaN being anything in particular. And you should generally avoid division by zero.

eerorika
  • 232,697
  • 12
  • 197
  • 326