Home  >  Article  >  Backend Development  >  Why does floating-point arithmetic differ between x86 and x64 in Visual Studio 2010?

Why does floating-point arithmetic differ between x86 and x64 in Visual Studio 2010?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 05:04:27185browse

Why does floating-point arithmetic differ between x86 and x64 in Visual Studio 2010?

Floating Point Arithmetic Discrepancy between x86 and x64

In Visual Studio 2010, a noticeable difference in floating-point arithmetic between x86 and x64 builds arises when comparing the values of certain expressions. This disparity manifests itself in the following code:

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;

x86 and x64 architectures handle the second expression, bLarger2, differently. In the x86 build, bLarger2 evaluates to true, while in the x64 build, it evaluates to false. This disparity is rooted in the computation of the expression (a * c) in floating-point operations.

Disparity Origins

The root of the discrepancy lies in the different floating-point units utilized by the two architectures: x87 for x86 and SSE for x64. The fundamental difference between the two units is their precision. The x87 unit employs higher than single precision (typically double precision) by default, while the SSE unit operates exclusively in single precision.

Remedying the Discrepancy

To resolve the discrepancy, the precision of the x87 unit can be manually configured to match that of the SSE unit. This can be achieved in 32-bit code by executing the following:

_controlfp(_PC_24, _MCW_PC);

By setting the precision to single precision, the evaluation of (a * c) in the bLarger2 expression will align with that of the x64 build, resulting in both bLarger1 and bLarger2 being set to false.

Conclusion

The difference in floating-point arithmetic between x86 and x64 builds stems from the distinct precision levels of the x87 and SSE floating-point units. By manually controlling the precision of the x87 unit to match that of the SSE unit, the discrepancy can be eliminated, ensuring consistent evaluation of expressions across both architectures.

The above is the detailed content of Why does floating-point arithmetic differ between x86 and x64 in Visual Studio 2010?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn