浮点加 - 给出奇怪的结果..! [英] Floating point addition - giving strange result..!

查看:172
本文介绍了浮点加 - 给出奇怪的结果..!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下代码:

  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);


code $
$ b $ p $显示以下输出:



1.0000001



但输出应该是 1.0000000 纠正我,如果我错了.. !!

解决方案

0.1与IEEE 754标准不是真正的0.1
$ b

0.1编码: 0 01111011 10011001100110011001101 (带浮点数)


  • 0表示指数(= 123 - > 123 - 127 = -4 (127是IEEE 754中的 bias>)

  • 10011001100110011001101尾数



要转换十进制数的尾数,我们有
1.10011001100110011001101 * 2 ^ -4 (base2)[1.xxx隐含在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)


When executing the following code:

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);
    }
}

The following output is displayed:

1.0000001

But output should be 1.0000000, right? Correct me if I'm wrong..!!

解决方案

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)

这篇关于浮点加 - 给出奇怪的结果..!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆