本文介绍了双倍减去双精度后的精度损失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧我有以下代码块:

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

System.out.println(zoom);

现在,缩放变量是double类型的,初始设置为1。结果是1 - .05 = .95; .95 - .05 = .9; .9 - .05 = .85;等等。这似乎并不是这样,虽然当我打印结果,你可以看到下面:




  • 0.95

  • 0.8999999999999999

  • 0.8499999999999999
  • 0.7999999999999998
  • 0.7499999999999998
  • 0.6999999999999997


希望有人能够清楚地解释。我搜索了互联网,我读到它有一些限制,当我们以二进制存储浮动,但我还是不太明白。我的问题的解决方案并不是很重要,但是我想理解这种行为。 解决方案

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

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

...输出 0.30000000000000004 / p>

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

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


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.

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

08-24 08:44