假设我的计算机使用 IEEE 754 浮点编码,我想知道以下函数返回 false 的最小数字是多少:
constexpr bool test(const unsigned long long int x)
{
return static_cast<unsigned long long int>(static_cast<double>(x)) == x;
}
假设我的计算机使用 IEEE 754 浮点编码,我想知道以下函数返回 false 的最小数字是多少:
constexpr bool test(const unsigned long long int x)
{
return static_cast<unsigned long long int>(static_cast<double>(x)) == x;
}
IEEE-754 中a 的尾数double
是 53 位(52 位和一个隐藏,非常技术性)。这意味着如果其中的最高位x
高于 52 位,并且一些低位非零,则比较将失败。
您可以通过编写一段代码来发现这一点:
unsigned long long x = 0x1;
while(x > 0)
{
x <<= 1ULL;
if (!test(x+1))
{
cout << "x=" << hex << x << endl;
break;
}
}
编辑:在实际测试后稍微修正了代码。
它确实x=20000000000000
按预期打印。
或者,如果您想使用<limits>
,您可以通过以下方式获得相同的结果:
numeric_limits<double> n;
cout << "digits=" << dec << n.digits << " -> " << hex << (1ULL << n.digits) << endl;