简体   繁体   English

为什么0.1的浮点表示以1结尾?

[英]Why does the floating point representation of 0.1 end in 1?

I've been writing a decimal to single-precision IEEE754 floating-point converter, and I found a few discrepancies with numbers like 0.1 and 0.2我一直在写一个小数到单精度 IEEE754 浮点转换器,我发现了一些数字的差异,比如 0.1 和 0.2

Let's take 0.1, the first step would be converting it into a simple binary representation (multiplying the fractional part by 2 and taking the integral part) This gives me a well-known recurring binary pattern (001100110011...)让我们取 0.1,第一步是将其转换为简单的二进制表示(将小数部分乘以 2 并取整数部分)这给了我一个众所周知的循环二进制模式(001100110011 ...)

The final binary representation of 0.1 (up to 26-bits) is 0. 00 0110 0110 0110 0110 0110 0110. 0.1(最多 26 位)的最终二进制表示为 0. 00 0110 0110 0110 0110 0110 0110。

To fit it into a 32-bit floating-point number, the next step is to normalize it by shifting the decimal point 4 times to the right, removing the leading 1., and truncating it to 23 bits.为了将其放入 32 位浮点数,下一步是通过将小数点向右移动 4 次,删除前导 1.,并将其截断为 23 位来对其进行归一化。 This leaves me with 10011001100110011001100. Most programming languages give me 10011001100110011001101 (with the last bit 1 instead of 0).这给我留下了 10011001100110011001100。大多数编程语言给我 10011001100110011001101(最后一位是 1 而不是 0)。 What am I doing wrong here?我在这里做错了什么?

... removing the leading 1., and truncating it to 23 bits. ... 删除前导 1.,并将其截断为 23 位。

Wrong operation: round , not truncate .错误操作: round ,而不是truncate Wrong order of operations - round, then remove the leading 1.错误的操作顺序 - 舍入,然后删除前导 1。

... still have no idea how it gets flipped though ...仍然不知道它是如何被翻转的

The infinite exact binary answer rounded to the closest float .无限精确的二进制答案四舍五入到最接近的float


With common float32 , the significand is 24-bit *1 .对于普通的float32 ,有效数是 24 位*1 Conversion of values with more than 24-bits is usually a round *2 , not truncate.超过 24 位的值的转换通常是一个round *2 ,而不是截断。 The remaining bits were 110_0110_...其余位是 110_0110_...

        123 4567 8901 2345 6789 0123 4
0 . 00 0110 0110 0110 0110 0110 0110 0110 0110 ...
        ^----------------------------^
0 . 00 0110 0110 0110 0110 0110 0110 1 rounded
         10 0110 0110 0110 0110 0110 1 encoded 23-bits

The rounding happens before the leading bit is removed as part of the encoding as the most significant bit place may change.舍入发生在前导位作为编码的一部分被删除之前,因为最高有效位的位置可能会改变。


Notes:笔记:

0.000110011001100110011001100           (binary) = 0.0999999940395355224609375000 (decimal)
0.0001100110011001100110011001100110... (binary) = 0.1                            (decimal)
0.000110011001100110011001101 (closer)  (binary) = 0.1000000014901161193847656250 (decimal)
 
        

*1 Most significant 1 bit implied, 23-bits explicitly coded. *1隐含最高有效 1 位,显式编码 23 位。
*2 Round to nearest, ties to even. *2四舍五入到最接近,并列到偶数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM