Home >Backend Development >C++ >Why Does Floating Point Arithmetic Differ Between x86 and x64 Architectures?
Difference in Floating Point Arithmetic Between x86 and x64
When executing an identical piece of code on MS VS 2010 for both x86 and x64 architectures (both running on a 64-bit machine), a notable difference in floating point arithmetic emerged.
Consider the following code snippet:
float a = 50.0f; float b = 65.0f; float c = 1.3f; float d = a * c; bool bLarger1 = d < b; bool bLarger2 = (a * c) < b;
In both x86 and x64 builds, bLarger1 remains false (d is set to 65.0). However, in the x64 build, bLarger2 is false, while in the x86 build, it is true.
The discrepancy arises from the expression bLarger2 = (a * c) < b. The generated code reveals that under x86, the evaluation is performed in the x87 unit, which operates at higher-than-single-precision (generally double precision), whereas under x64, the evaluation is performed in the x64 unit, which performs pure single-precision calculations.
To ensure that the 32-bit unit performs calculations in single precision, the following control word can be set:
_controlfp(_PC_24, _MCW_PC);
This will result in both booleans being set to false in the 32-bit program.
The underlying issue stems from the inherent difference between the x87 and SSE floating point units. The x87 unit uses identical instructions for both single and double precision types, while the SSE unit employs distinct instructions for each. Consequently, the compiler can exert more control over calculation precision in the SSE unit.
Overall, the disparity between x86 and x64 floating point arithmetic arises from the operating modes of the respective floating point units. To ensure consistent behavior, it is recommended to explore options for persuading the compiler to emit SSE instructions even for 32-bit targets.
The above is the detailed content of Why Does Floating Point Arithmetic Differ Between x86 and x64 Architectures?. For more information, please follow other related articles on the PHP Chinese website!