【问题标题】:Round down operation result in IEEE 754IEEE 754 中的四舍五入运算结果
【发布时间】:2020-05-06 21:51:08
【问题描述】:

对于在 IEEE 754(浮点数,32 位)中使用单精度值的操作,有没有办法以某种方式调节两个操作数,以确保在无法获得精确结果时,运算结果被向下舍入?换句话说,如何强制舍入到 -Inf?

例子:

  • 典型结果(使用“四舍五入”):1.0f / 3.0f = 0.3333333432674407958984375f
  • 预期结果(使用“向下舍入”):1.0f / 3.0f = 0.333333313465118408203125f

作为附加信息,我将在 C99 中执行此操作,并且(不幸的是)无法配置 FPU。

【问题讨论】:

  • Re“在 C99 中,并且(不幸的是)无法配置 FPU”:为什么这么说? C 1999 在第 7.6 节中为此指定了设施,带有 <fenv.h> 标头。

标签: floating-point rounding ieee-754


【解决方案1】:

C 1999 和当前的 C 标准都指定了设置浮点舍入模式的工具。但是,并非所有 C 实现都支持它们。在这样做的实现中,以下代码将保存先前的舍入模式,执行舍入到负无穷大的操作,并恢复先前的舍入模式:

//  Declare identifiers for accessing floating-point environment.
#include <fenv.h>


void foo(void *data)
{
    //  Inform compiler this code accesses the floating-point environment.
    #pragma STDC FENV_ACCESS ON

    //  Save caller's rounding mode.
    int PreviousRoundingMode = fegetround();

    //  Set desired rounding mode.
    if (fesetround(FE_DOWNWARD) != 0)
    {
        //  fesetround failed.  Handle error.
    }

    //  Insert here code to perform desired operations.

    //  Restore previous rounding mode.
    fesetround(PreviousRoundingMode);
}
}

请注意,+*-/fma 等基本运算可以预期符合舍入模式,但数学库函数如 sinlog 可能不会。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2013-02-09
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多