如何避免 Java 中的浮点数或双精度数的浮点精度错误?

How to avoid floating point precision errors with floats or doubles in Java?(如何避免 Java 中的浮点数或双精度数的浮点精度错误?)
本文介绍了如何避免 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 中的浮点数或双精度数的浮点精度错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)