由于浮点舍入误差,非整数的平方根可以变成整数吗?
在另一个不相关的互联网论坛中,有人提出了如何检查给定数字的平方根是否是整数的问题。现在,这本身就是一个微不足道的家庭作业问题,但我开始怀疑这种幼稚的方法是否在所有情况下都是正确的。也就是说,在伪代码中:
declare x, y as double
input x
y = sqrt(x)
if round(y) = y then
output "Is integer"
else
output "Isn't integer"
是否可以输入这样的 x
,使得 x
本身不是是一个整数(或者是一个整数)不是另一个整数的平方),但由于浮点错误,sqrt(x)
将是并且是整数?
In another unrelated Internet forum a question was asked on how to check if a square root of a given number is an integer. Now in and of itself that is a trivial homework question, but I started to wonder if the naïve approach is correct under all circumstances. That is, in pseudocode:
declare x, y as double
input x
y = sqrt(x)
if round(y) = y then
output "Is integer"
else
output "Isn't integer"
Is it possible to enter such an x
, that x
itself would not be an integer (or an integer which is not a square of another integer) but sqrt(x)
would be and integer because of floating point errors?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是:当 x 位于机器 epsilon 的边缘时。
考虑 x = 1.00...0001,它仍然可以用二进制形式表示,与 1.0 不同。该数字的平方根将为 1.0,产生假正值。
Yes: when x is on the edge of Machine epsilon.
Consider x = 1.00...0001, where it is still representable in its binary form, not identical to 1.0. A square root of this number will give 1.0, yielding false poitive.
1.0 以上的下一个可表示浮点数(C 中的
nextafter(1.0)
)的平方根可能会计算为 1.0。The square root of the next representable floating-point number above 1.0 (
nextafter(1.0)
in C) could plausibly evaluate to 1.0.首先,如果数字太大以至于精度不能延伸到小数点,那么你只会得到整数,但它们不正确,所以我想你不关心这种情况。
关于精确结果:如果您有 IEE754 浮点数,测试应该相当容易。只需取一个完美整数平方的 double,将其二进制表示形式增加或减少一位,然后检查平方根是否是精确整数。我相信,标准浮点运算要求精确到最后一位的 0.5 个单位,因此整数实际上可能是正确的最接近的可表示平方根。
First off, if the numbers are so large that the precision does not extend down to the decimal point, then you'll only get integers, but they're not correct, so I suppose you don't care about that case.
Concerning exact results: This should be fairly easy to test if you have IEE754 floats. Just take a double that is a perfect integral square, increment or decrement its binary representation by one bit, and then check if the square root is an exact integer. The standard floating point operations are required to be exact to 0.5 units in last place, I believe, so it's possible that the integer is actually the correct nearest representable square root.
当然:
这会导致(C#)
Of course:
This results in (C#)
将 x 作为像 1+epsilon 这样的浮点数输入当然可以。但对于非平方整数,只要整数足够大,它也可以工作。
例如(c#)
Feeding x as a float like 1+epsilon will of course work. But for a non-square integer it also works given the integer is large enough.
For example (c#)