问题描述
我有一个非常烦人的问题,即 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 精确表示为 float 或 double.由于这种表示错误,结果与您的预期略有不同.
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
doubletype, 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
BigDecimalcan 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 中的浮点数或双精度数的浮点精度错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)