The code snippet provided demonstrates a discrepancy in floating-point calculation results when using optimization on different compilers. On Visual Studio 2008 and g without optimization, the code produces the expected output. However, with g optimization enabled (O1 - O3), it exhibits incorrect results.
To understand the root cause of this behavior, it's essential to note that Intel x86 processors handle floating-point computations internally using 80-bit extended precision. In contrast, the double data type in C typically has a width of 64 bits.
Optimization levels influence how often floating-point values from the CPU are stored in memory. This can lead to rounding errors when values are converted from 80-bit precision to 64-bit precision during storage.
To ensure consistent floating-point results across optimization levels, gcc provides the -ffloat-store option. By using this option, floating-point values are always stored in memory, preventing any rounding errors caused by register storage.
Alternatively, using the long double data type, which usually has a width of 80 bits on gcc, can eliminate the rounding issue altogether.
It's intriguing that Visual Studio 2008 provides correct results even with extended floating-point precision enabled. This suggests that VS2008 handles rounding and optimization differently compared to g .
While it's not strictly necessary to use -ffloat-store, it is recommended when targeting systems that use extended floating-point precision internally to ensure predictable behavior across optimization levels.
For x86_64 builds, this issue does not arise because compilers use SSE registers for float and double by default, eliminating the use of extended precision. The gcc compiler option -mfpmath allows you to control this behavior.
The above is the detailed content of Why Do Floating-Point Results Differ With Optimization in Different Compilers?. For more information, please follow other related articles on the PHP Chinese website!