文字和计算中的浮点精度 [英] Floating point precision in literals vs calculations

查看:156
本文介绍了文字和计算中的浮点精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么Java语言中的浮点数可以用文字初始化的时候表示精确的数值,但是当它们代表一些计算的结果时它们是近似的。
例如:

  double num1 = 0.3; 
double num2 = 0.1 + 0.2;
System.out.println(num1);
System.out.println(num2);

为什么结果是:

<$ p $而不是: 0.3
0.30000000000000004

而不是:

  0.30000000000000004 
0.30000000000000004

当没有0.3的确切的二进制表示。
我知道BigDecimal类,但我不太明白这个原始数字的不一致性。

解决方案

三个数字可以完全表示为 double 。得到不同结果的原因是,在 0.1 加到 0.2 之后的值与<$有不同的表示误差C $ C> 0.3 。在打印结果( demo )时,大约5.5E-17的差异足以导致差异。 p>

  double a = 0.2; 
double b = 0.1;
double c = 0.3;
double d = a + b;
double e = d-c; //这是5.551115123125783E-17


I'm wondering why floating point numbers in Java can represent exact value when they are initialized as literals, but they are approximate when they represent result of some calculation. For example:

double num1 = 0.3;
double num2 = 0.1 + 0.2;
System.out.println(num1);
System.out.println(num2);

why the result is:

0.3
0.30000000000000004

and not:

0.30000000000000004
0.30000000000000004

When there is no exact binary representation of 0.3. I know the BigDecimal class, but I don't quite understand this primitive numbers inconsistency.

解决方案

None of the three numbers can be represented exactly as a double. The reason that you get different results is that the value after adding 0.1 to 0.2 has a different representation error than 0.3. The difference of about 5.5E-17 is enough to cause a difference when printing out the result (demo).

double a = 0.2;
double b = 0.1;
double c = 0.3;
double d = a+b;
double e = d-c; //  This is 5.551115123125783E-17

这篇关于文字和计算中的浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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