GCC problem with raw double type comparisons

Posted by Monomer on Stack Overflow See other posts from Stack Overflow or by Monomer
Published on 2010-03-23T05:47:25Z Indexed on 2010/03/23 5:53 UTC
Read the original article Hit count: 222

Filed under:
|
|
|
|

I have the following bit of code, however when compiling it with GCC 4.4 with various optimization flags I get some unexpected results when its run.

#include <iostream>

int main()
{
   const unsigned int cnt = 10;
   double lst[cnt] = { 0.0 };
   const double v[4] = { 131.313, 737.373, 979.797, 731.137 };

   for(unsigned int i = 0; i < cnt; ++i) {
      lst[i] = v[i % 4] * i;
   }

   for(unsigned int i = 0; i < cnt; ++i) {
      double d = v[i % 4] * i;
      if(lst[i] != d) {
         std::cout << "error @ : " << i << std::endl;
         return 1;
      }
   }
   return 0;
}
  • when compiled with: "g++ -pedantic -Wall -Werror -O1 -o test test.cpp" I get the following output: "error @ : 3"

  • when compiled with: "g++ -pedantic -Wall -Werror -O2 -o test test.cpp" I get the following output: "error @ : 3"

  • when compiled with: "g++ -pedantic -Wall -Werror -O3 -o test test.cpp" I get no errors

  • when compiled with: "g++ -pedantic -Wall -Werror -o test test.cpp" I get no errors

I do not believe this to be an issue related to rounding, or epsilon difference in the comparison. I've tried this with Intel v10 and MSVC 9.0 and they all seem to work as expected. I believe this should be nothing more than a bitwise compare.

If I replace the if-statement with the following: if (static_cast<long long int>(lst[i]) != static_cast<long long int>(d)), and add "-Wno-long-long" I get no errors in any of the optimization modes when run.

If I add std::cout << d << std::endl; before the "return 1", I get no errors in any of the optimization modes when run.

Is this a bug in my code, or is there something wrong with GCC and the way it handles the double type?

© Stack Overflow or respective owner

Related posts about c++

Related posts about gcc