如何检查float是否可以精确地表示为整数

如何检查float是否可以精确地表示为整数

本文介绍了如何检查float是否可以精确地表示为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种合理有效的方式来确定浮点值( double )是否可以由整型数据类型( long ,64位)。

I'm looking to for a reasonably efficient way of determining if a floating point value (double) can be exactly represented by an integer data type (long, 64 bit).

我最初的想法是检查指数,看看它是否是 0 (或更准确地说 127 )。但是这不行,因为 2.0 将是e = 1 m = 1 ...

My initial thought was to check the exponent to see if it was 0 (or more precisely 127). But that won't work because 2.0 would be e=1 m=1...

所以基本上,我被卡住了我有一种感觉,我可以用咬面具做到这一点,但是我现在不知道如何做到这一点。

So basically, I am stuck. I have a feeling that I can do this with bit masks, but I'm just not getting my head around how to do that at this point.

那么我怎么能检查一下双是否可以代表一个长?

So how can I check to see if a double is exactly representable as a long?

谢谢

推荐答案

这是一种在大多数情况下可以工作的方法。我不知道如果你给它,它将如何/将如何破坏 NaN INF ,非常大(溢出)数字...

(虽然我认为他们都会返回错误 - 不能完全代表。)

Here's one method that could work in most cases. I'm not sure if/how it will break if you give it NaN, INF, very large (overflow) numbers...
(Though I think they will all return false - not exactly representable.)

您可以:


  1. 将其转换为整数。

  2. 将其转换为浮点。

  3. 与原始价值比较

如下所示:

double val = ... ;  //  Value

if ((double)(long long)val == val){
    //  Exactly representable
}

floor() ceil()也是公平的游戏(尽管它们可能会失败,如果值溢出一个整数):

floor() and ceil() are also fair game (though they may fail if the value overflows an integer):

floor(val) == val
ceil(val) == val






这是一个凌乱的位掩码解决方案:

这使用联合类型惩罚,并假定IEEE双精度。

int representable(double x){
    //  Handle corner cases:
    if (x == 0)
      return 1;

    //  -2^63 is representable as a signed 64-bit integer, but +2^63 is not.
    if (x == -9223372036854775808.)
      return 1;

    //  Warning: Union type-punning is only valid in C99 TR2 or later.
    union{
        double f;
        uint64_t i;
    } val;

    val.f = x;

    uint64_t exp = val.i & 0x7ff0000000000000ull;
    uint64_t man = val.i & 0x000fffffffffffffull;
    man |= 0x0010000000000000ull;  //  Implicit leading 1-bit.

    int shift = (exp >> 52) - 1075;
    //  Out of range
    if (shift < -52 || shift > 10)
        return 0;

    //  Test mantissa
    if (shift < 0){
        shift = -shift;
        return ((man >> shift) << shift) == man;
    }else{
        return ((man << shift) >> shift) == man;
    }
}

这篇关于如何检查float是否可以精确地表示为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 12:30