Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nan behaves differently in #pragma cpp

I am learning about the NaN datatype, so, I ran a code to understand it and it goes well, the code worked as expected, but when I add a line #pragma GCC optimize("Ofast") in my code then, it behaves unexpected. I am curious why??

#pragma GCC optimize("Ofast")
// C++ code to check for NaN exception
// using "==" operator
#include <cmath>
#include <iostream>
using namespace std;

// Driver Code
int main()
{
  float a = sqrt(2);
  float b = sqrt(-2);

  // Returns true, a is real number
  // prints "Its a real number"
  a == a ? cout << "Its a real number" << endl
    : cout << "Its NaN" << endl;

  // Returns false, b is complex number
  // prints "Its nan"
  b == b ? cout << "Its a real number" << endl
    : cout << "Its NaN" << endl;

  return 0;
}

The ouput without pragma is

Its a real number
Its NaN

But after using pragma it gives

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Its a real number
Its a real number

>Solution :

-Ofast turns on -ffast-math, which turns on -ffinite-math-only, which does the following (from the gcc documentation here: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html)

-ffinite-math-only

Allow optimizations for floating-point arithmetic that assume that
arguments and results are not NaNs or +-Infs.

This option is not turned on by any -O option since it can result in
incorrect output for programs that depend on an exact implementation
of IEEE or ISO rules/specifications for math functions. It may,
however, yield faster code for programs that do not require the
guarantees of these specifications.

I think the "-O option" part is wrong since the -Ofast documentation says it "disregards strict standards compliance". That, or by "any -O option" they mean -O1, -O2, -O3.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading