Fixing Floating-Point Errors with the GCC Compiler
Depending on your machine architecture, you may experience some variability in the results of floating-point-based operations in C or C++ code. For example, the expression sin( val ) == sin( val ) may evaluate as false on an Intel Pentium 4 processor if the variable val holds a floating-point value with double precision. This page highlights a solution for this problem which is provided by the GCC compiler.
The following program can be used to test if your machine exhibits the erroneous behaviour. The program first creates a variable called val to store a floating point value with double precision. The variable is initialised with a value of 1.0 and is not changed in the rest of the program. A number of assert statements are then executed to compare the results of two invocations of the same function on this variable. If all of the assertions evaluate as true, the program exits normally. If any of the assertions fail, the program will display a message and then exit.
#include <cassert>
#include <cmath>
int main()
{
const double val( 1.0 );
assert( cos( val ) == cos( val ) );
assert( sin( val ) == sin( val ) );
assert( tan( val ) == tan( val ) );
assert( log( val ) == log( val ) );
return 0;
}
Before compiling the code, please remember to add angle brackets around the names of the header files in the two #include statements. The program can be compiled with the g++ compiler and does not require any non-standard header files or libraries. For example:
$ g++ float_test.cpp
If you find that any of the assertions fail when the program is executed, you can try enabling special options provided by the GCC compiler to help overcome floating-point errors. For example:
$ g++ -mfpmath=sse -msse2 float_test.cpp
These options only affect compilation on certain processors. Versions 4 and newer of the Intel Pentium range and recent AMD Athlon processors are among those supported.
For more information on this issue and other approaches to solving it, please see the Links section below.
Links
- A detailed description of the problem on the C++ FAQ website
- The GCC documentation website
- The Hardware Models and Configurations section
- The Intel 386 and AMD x86-64 Options sub-section