Portably Adjusting Floating-Point Rounding Behavior
The need to modify the IEEE 754 rounding mode arises in various scenarios. This article elucidates efficient methods to achieve this, both in portable C and using x86 assembly language.
C Solution
C99 provides a comprehensive solution for manipulating rounding modes:
#include <fenv.h> #pragma STDC FENV_ACCESS ON int main() { // Preserve the initial rounding mode const int roundingMode = fegetround(); // Set the desired rounding mode (towards zero) fesetround(FE_TOWARDZERO); // Perform floating-point operations... // Revert to the original rounding mode fesetround(roundingMode); return 0; }
x86 Assembly Solution
On platforms not supporting C99, x86 assembly offers an alternative:
x87 Floating-Point Unit: Use fldcw to adjust the rounding mode.
SSE Unit: Use ldmxcsr to configure the SIMD rounding mode.
MSVC-Specific Solution
Microsoft Visual C provides the non-standard _controlfp() function:
unsigned int roundingMode = _controlfp(0, 0); _controlfp(_RC_CHOP, _MCW_RC); // ... _controlfp(roundingMode, _MCW_RC);
Rounding Mode Constants
The following table provides a reference for rounding mode constants:
Rounding Mode | C Name | MSVC Name |
---|---|---|
Nearest | FE_TONEAREST | _RC_NEAR |
Towards Zero | FE_TOWARDZERO | _RC_CHOP |
Positive Infinity | FE_UPWARD | _RC_UP |
Negative Infinity | FE_DOWNWARD | _RC_DOWN |
The above is the detailed content of How Can I Portably Adjust Floating-Point Rounding Behavior in C and Assembly?. For more information, please follow other related articles on the PHP Chinese website!