如何在 Java 中使用浮点数或双精度数来避免浮点精度错误? [英] How to avoid floating point precision errors with floats or doubles in Java?

查看:37
本文介绍了如何在 Java 中使用浮点数或双精度数来避免浮点精度错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常烦人的问题,即 Java 中的浮点数或双数的长总和.基本上的想法是,如果我执行:

I have a very annoying problem with long sums of floats or doubles in Java. Basically the idea is that if I execute:

for ( float value = 0.0f; value < 1.0f; value += 0.1f )
    System.out.println( value );

我得到的是:

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001

我知道浮动精度误差是累积的,但是,如何摆脱这个?我尝试使用 doubles 将错误减半,但结果仍然相同.

I understand that there is an accumulation of the floating precision error, however, how to get rid of this? I tried using doubles to half the error, but the result is still the same.

有什么想法吗?

推荐答案

没有将 0.1 精确表示为 floatdouble.由于此表示错误,结果与您的预期略有不同.

There is a no exact representation of 0.1 as a float or double. Because of this representation error the results are slightly different from what you expected.

您可以使用的几种方法:

A couple of approaches you can use:

  • 当使用 double 类型时,只显示你需要的数字.在检查相等性时,无论哪种方式都允许有一个小的容差.
  • 或者使用允许您存储要精确表示的数字的类型,例如 BigDecimal 可以精确表示 0.1.
  • When using the double type, only display as many digits as you need. When checking for equality allow for a small tolerance either way.
  • Alternatively use a type that allows you to store the numbers you are trying to represent exactly, for example BigDecimal can represent 0.1 exactly.

BigDecimal 的示例代码:

BigDecimal step = new BigDecimal("0.1");
for (BigDecimal value = BigDecimal.ZERO;
     value.compareTo(BigDecimal.ONE) < 0;
     value = value.add(step)) {
    System.out.println(value);
}

在线查看:ideone

这篇关于如何在 Java 中使用浮点数或双精度数来避免浮点精度错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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