更改浮点舍入模式 [英] Change floating point rounding mode

查看:157
本文介绍了更改浮点舍入模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是改变IEEE 754的舍入模式*浮点数的最有效方法是什么?便携式的C函数将是很好的,但使用x86汇编的解决方案是确定了。

What is the most efficient way to change the rounding mode* of IEEE 754 floating point numbers? A portable C function would be nice, but a solution that uses x86 assembly is ok too.

*我指的是朝着最接近标准的舍入模式,迈向零,向正/负无穷大。

*I am referring to the standard rounding modes of towards nearest, towards zero, and towards positive/negative infinity

推荐答案

这是标准的C方案:

#include <fenv.h>
#pragma STDC FENV_ACCESS ON

// store the original rounding mode
const int originalRounding = fegetround( );
// establish the desired rounding mode
fesetround(FE_TOWARDZERO);
// do whatever you need to do ...

// ... and restore the original mode afterwards
fesetround(originalRounding);

在缺乏C99支持向后平台上,可能需要求助于大会。在这种情况下,你可能要为双方的x87单位取整(通过 FLDCW 指令)和SSE(通过 ldmxcsr 指令)。

On backwards platforms lacking C99 support, you may need to resort to assembly. In this case, you may want to set the rounding for both the x87 unit (via the fldcw instruction) and SSE (via the ldmxcsr instruction).

修改
你并不需要求助于大会MSVC。您可以使用(完全非标) _control_fp()而不是:

unsigned int originalRounding = _control_fp(0, 0);
_control_fp(_RC_CHOP, _MCW_RC);
// do something ...
_control_fp(originalRounding, _MCW_RC);

您可以阅读更多关于_control_fp() MSDN上

You can read more about _control_fp( ) on MSDN.

和,只是为了完整性,对于舍入模式的宏名脱codeR环:

And, just for completeness, a decoder ring for the macro names for rounding modes:

rounding mode    C name         MSVC name
-----------------------------------------
to nearest       FE_TONEAREST   _RC_NEAR
toward zero      FE_TOWARDZERO  _RC_CHOP
to +infinity     FE_UPWARD      _RC_UP
to -infinity     FE_DOWNWARD    _RC_DOWN

这篇关于更改浮点舍入模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆