在Java中的双重算术中得到错误的答案 [英] Getting wrong answer in double arithmetic in Java

查看:109
本文介绍了在Java中的双重算术中得到错误的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

双重计算产生奇数结果

我正在写一个Java中的程序处理了大量的双重算术。我最终得到了我需要添加0.6666666666666666和-0.666666666666667的点。但是,我得到的答案是-3.3306690738754696E-16。

I'm writing a program in Java that deals with a lot of double arithmetic. I eventually get to the point where I need to add 0.6666666666666666 and -0.666666666666667. However, the answer that I get is -3.3306690738754696E-16.

换句话说,

double d1 = 0.6666666666666666;
double d2 = -0.666666666666667;
System.out.println(d1 + d2);

打印出-3.3306690738754696E-16。为什么会发生这种情况?

prints out "-3.3306690738754696E-16". Why is this happening?

提前谢谢。

推荐答案

double 值不能精确地表示所有值,这是一个例子。您可以使用 BigDecimal

double values cannot represent all values precisely and this is such an example. You can use BigDecimal instead:

BigDecimal bd1 = new BigDecimal("0.6666666666666666");
BigDecimal bd2 = new BigDecimal("-0.666666666666667");
System.out.println(bd1.add(bd2));

输出:

-4E-16

这篇关于在Java中的双重算术中得到错误的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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