双倍减去双精度后的精度损失 [英] Loss of precision after subtracting double from double

查看:161

Java使用 IEEE-754 浮点数。他们不是很精确。着名的例子是:

  System.out.println(0.1d + 0.2d); 

...输出 0.30000000000000004 / p>

您所看到的只是这种不精确的症状。你可以通过使用 double 而不是 float 来提高精确度。

如果你正在处理财务计算,你可能更喜欢 BigDecimal to float double


Possible Duplicate:
Retain precision with Doubles in java

Alright so I've got the following chunk of code:

int rotation = e.getWheelRotation();
if(rotation < 0)
    zoom(zoom + rotation * -.05); 
else if(zoom - .05 > 0)
    zoom(zoom - rotation * .05);

System.out.println(zoom);

Now, the zoom variable is of type double, initially set to 1. So, I would expect the results to be like 1 - .05 = .95; .95 - .05 = .9; .9 - .05 = .85; etc. This appears to be not the case though when I print the result as you can see below:

  • 0.95
  • 0.8999999999999999
  • 0.8499999999999999
  • 0.7999999999999998
  • 0.7499999999999998
  • 0.6999999999999997

Hopefully someone is able to clearly explain. I searched the internet and I read it has something to do with some limitations when we're storing floats in binary but I still don't quite understand. A solution to my problem is not shockingly important but I would like to understand this kind of behavior.

解决方案

Java uses IEEE-754 floating point numbers. They're not perfectly precise. The famous example is:

System.out.println(0.1d + 0.2d);

...which outputs 0.30000000000000004.

What you're seeing is just a symptom of that imprecision. You can improve the precision by using double rather than float.

If you're dealing with financial calculations, you might prefer BigDecimal to float or double.

这篇关于双倍减去双精度后的精度损失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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