【问题标题】:From what number the following conversion integer -> double -> integer is not valid?以下转换整数 -> 双倍 -> 整数从哪个数无效?
【发布时间】:2013-04-16 19:34:03
【问题描述】:

假设我的计算机使用 IEEE 754 浮点编码,我想知道以下函数返回 false 的最小数字是多少:

constexpr bool test(const unsigned long long int x)
{
    return static_cast<unsigned long long int>(static_cast<double>(x)) == x;
}

【问题讨论】:

  • 2**53 + 1,我想。换一种说法 0x20000000000001
  • 糟糕,问题是针对 "==" 而不是 "!="

标签: c++ integer double floating-accuracy floating-point-precision


【解决方案1】:

IEEE-754 中double 的尾数是 53 位(52 位和 1 位隐藏,技术含量很高)。这意味着如果x 中的最高位高于第 52 位,并且一些低位非零,则比较将失败。

你可以通过编写一段代码来发现这一点:

unsigned long long x = 0x1;

while(x > 0)
{
   x <<= 1ULL;
   if (!test(x+1))
   {
      cout << "x=" << hex << x << endl;
      break;

   }
}

编辑:在实际测试后稍微修正了代码。

它确实像预测的那样打印x=20000000000000

或者,如果你想使用&lt;limits&gt;,你可以达到同样的效果:

numeric_limits<double> n;
cout << "digits=" << dec << n.digits << " -> " << hex << (1ULL << n.digits) << endl;

【讨论】:

  • 是否可以在编译时使用 std::numeric_limits 计算这个数字?
  • 可能。在我进行了一些实验后,让我回复你 - 我不知道究竟是哪个领域做到了这一点,但我认为可以做到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 2014-11-10
  • 2015-06-29
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
相关资源
最近更新 更多