"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-15
Browse:710

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 

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3