浮点加法 - 给出奇怪的结果..!

Gok*_* KP 1 java floating-point floating-accuracy

执行以下代码时:

public class FPoint {
    public static void main(String[] args) {
        float f = 0.1f;
        for(int i = 0; i<9; i++) {
            f += 0.1f;
        }
        System.out.println(f);
    }
}
Run Code Online (Sandbox Code Playgroud)

将显示以下输出:

1.0000001

但输出应该是1.0000000,对吗?如我错了请纠正我..!!

Fab*_* Sa 7

0.1 is not really "0.1" with IEEE 754 Standard.

0.1 is coded : 0 01111011 10011001100110011001101 (with float number)

  • 0 is the sign (= positive)
  • 01111011 the exponent (= 123 -> 123 - 127 = -4 (127 is the bias in IEEE 754))
  • 10011001100110011001101 the mantissa

To convert the mantissa in decimal number we have 1.10011001100110011001101*2^-4(base2) [the 1.xxx is implicit in IEEE 754]

= 0.000110011001100110011001101(base2)

= 1/2^4 + 1/2^5 + 1/2^8 + 1/2^9 + 1/2^12 + 1/2^13 + 1/2^16 + 1/2^17 + 1/2^20 + 1/2^21 + 1/2^24 + 1/2^25 + 1/2^27 (base10)

= 1/16 + 1/32 + 1/256 + 1/512 + 1/4096 + 1/8192 + 1/65536 + 1/131072 ...(base10)

= 0.10000000149011612(base10)