Home > Article > Backend Development > Why Does Floating Point Arithmetic in x86 and x64 Architectures Produce Different Results?
Understanding the Discrepancy in Floating Point Arithmetic between x86 and x64
In the realm of computer programming, the distinction in how floating point arithmetic is handled between x86 and x64 architectures can lead to unexpected outcomes. This query explores such a discrepancy, specifically involving the comparison of two floating point values in Microsoft Visual Studio 2010 builds.
The Problem
Executing the following code snippet in x86 and x64 builds on the same 64-bit machine reveals a discrepancy:
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;
The boolean bLarger1 remains false in both builds, while bLarger2 is false in x64 but true in x86. This inconsistency raises questions about the underlying mechanics of floating point arithmetic in these architectures.
The Cause
The crux of the problem lies in the evaluation of the expression:
bool bLarger2 = (a * c) < b;
Examining the generated assembly code for both x86 and x64 reveals a key difference. In x64, the calculation is performed using pure single-precision instructions. In contrast, x86 utilizes the x87 floating-point unit, which operates at a higher precision (double-precision by default).
The Explanation
This distinction stems from the fundamental differences between the x87 FPU and the x64 SSE unit. The x87 unit employs the same instructions for both single and double-precision calculations, leading to a level of imprecision in single-precision operations. On the other hand, the SSE unit uses distinct instructions for each precision, ensuring accurate single-precision computations.
The Solution
To resolve this discrepancy in the 32-bit (x86) build, it is possible to force the x87 unit to perform single-precision calculations by using the following control flag:
_controlfp(_PC_24, _MCW_PC);
This will result in both boolean variables (bLarger1 and bLarger2) being set to false in both x86 and x64 builds.
Conclusion
The discrepancy in floating point arithmetic between x86 and x64 stems from the differences in their underlying floating-point units. By understanding these distinctions and taking appropriate measures, such as forcing single-precision calculations in x86, programmers can ensure accurate and consistent results across different architectures.
The above is the detailed content of Why Does Floating Point Arithmetic in x86 and x64 Architectures Produce Different Results?. For more information, please follow other related articles on the PHP Chinese website!