简体   繁体   English

更改浮点舍入模式

[英]Change floating point rounding mode

What is the most efficient way to change the rounding mode* of IEEE 754 floating point numbers? 更改IEEE 754浮点数的舍入模式*的最有效方法是什么? A portable C function would be nice, but a solution that uses x86 assembly is ok too. 可移植的C函数会很好,但是使用x86汇编的解决方案也是可以的。

*I am referring to the standard rounding modes of towards nearest, towards zero, and towards positive/negative infinity *我指的是朝着最近,朝着零以及朝着正/负无穷大的标准舍入模式

This is the standard C solution: 这是标准的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);

On backwards platforms lacking C99 support, you may need to resort to assembly. 在缺乏C99支持的向后平台上,您可能需要求助于组装。 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). 在这种情况下,您可能想同时设置x87单元(通过fldcw指令)和SSE(通过ldmxcsr指令)的舍入。

Edit You don't need to resort to assembly for MSVC. 编辑您无需求助于MSVC的汇编。 You can use the (totally non-standard) _controlfp( ) instead: 您可以使用(完全非标准的) _controlfp( )

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

You can read more about _controlfp( ) on MSDN . 您可以在MSDN上阅读有关_controlfp()的更多信息。

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

this might help. 可能会有所帮助。

Edit: I would say you would need your own function. 编辑:我会说你需要自己的功能。 You can use assembly inside C. 您可以在C中使用汇编。

But if you register size is 64bits, round it to 32bit would make your calculations faster. 但是,如果您注册的大小为64位,则将其舍入为32位将使您的计算速度更快。 It will actually make it slower. 这实际上会使它变慢。 Remember 64bit calculations is easy for a 64 microprocessor rather than 2-32bit. 请记住,对于64位微处理器,而不是2-32位,64位计算很容易。 I don't know what exactly you want to achieve. 我不知道您到底想实现什么。 I know performance is on your criteria. 我知道性能取决于您的标准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM