Home > Backend Development > C++ > How Can I Portably Adjust Floating-Point Rounding Behavior in C and Assembly?

How Can I Portably Adjust Floating-Point Rounding Behavior in C and Assembly?

Linda Hamilton
Release: 2024-11-24 17:34:16
Original
934 people have browsed it

How Can I Portably Adjust Floating-Point Rounding Behavior in C and Assembly?

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;
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template