四舍五入到最接近的低级实现
我有一些低级问题:
假设我们得到了十进制数 0.1(我们可以通过写 1/10 来非常精确地表示它 - 但这不是一个解决方案)。转换为二进制数,这给了我们 0,00011 最后 4 位数字无限重复 (0,0001100110011....)。
现在假设我们想要将这个数字放入浮点表示中,例如 IEEE 754 单精度,并且我们想要对其进行舍入,以便得到最接近的可能表示,这给了我们
1 0111 1110 0101 0101 0101 0101 0101 011
(仅供参考:如果我们简单地截断,最后一位数字应该是 0 而不是 1)
现在,我的问题是:如何在软件中实现这一点?毕竟我们不能简单地使用一些
x=((x_floor-0.1)<(x_ceil-0.1))?x_floor:x_ceil;
因为这意味着“完美”0.1,这是我问题的核心。有什么想法吗?
I've got some low-level question:
Let's assume we've got the decimal number 0.1 (we can represent this very exactly by writing 1/10 - but that is not a solution). Converted into a binary number, this gives us
0,00011 with the last 4 digits infinitely repeated (0,0001100110011....).
So now assume we want to put this number into a floating point representation, e.g. IEEE 754 single precision and we want to round it so that the nearest possible representation, which gives us
1 0111 1110 0101 0101 0101 0101 0101 011
(fyi: the last digit should be a 0 instead of a 1 if we would simply truncate)
Now, my question is: How to achieve this in software? After all we can't simply use some
x=((x_floor-0.1)<(x_ceil-0.1))?x_floor:x_ceil;
as this would imply a "perfect" 0.1 which is the core of my problem. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想我已经对自己的问题有了一些答案:您可以通过检查以下对话内容来做出决定。如果要设置的话,可以四舍五入到ceil,因为看下面的例子:我们要将二进制数0.1001四舍五入到点后3位。如果我们将其四舍五入到 0.100,我们将产生 0,0001 的误差,就像我们将其四舍五入到 0,101 的情况一样。
但更有趣的是:如果要舍入的数字是 0,1001...1 - 在任何情况下舍入到 0.100 时所产生的误差都将大于舍入到 0.101 时的误差!对于实际对话后未设置位的情况,可以以类似的方式完成此“证明”
I think I've got some answer on my own question: You can decide by checking the following bit of the conversation. If it would be set, you can round to the ceil, because view the following example: we want to round the binary number 0.1001 to 3 digits after the dot. if we round it to 0.100, we would make an error of 0,0001 as well as in the case we round it to 0,101.
But more interesing: if the number to round is 0,1001...1 - the error we would make if we round to 0.100 would be bigger than the error when rounding to 0.101 in any case! This "proof" can be done in a similar way for the case of an unset bit following the actual conversation