Sure, here is the translation: JAVA:两个浮点数的差异

huangapple 未分类评论48阅读模式
英文:

JAVA: Difference in Two Floats

问题

double double1 = 0.174;
double double2 = 0.175;
double diff = Math.abs(double1 - double2);

diff 返回 0.0010000000000000009

现在我输入:

double double1 = 3.174;
double double2 = 3.175;
double diff = Math.abs(double1 - double2);

我期望 diff 返回相同的结果,但实际上返回了 9.999999999998899E-4
这种行为有原因吗?

英文:
double double1 = 0.174;
double double2 = 0.175;
double diff = Math.abs(double1 - double2);

diff returns 0.0010000000000000009

Now I type:

double double1 = 3.174;
double double2 = 3.175;
double diff = Math.abs(double1 - double2);

I am expecting diff to return the same result, but it returns 9.999999999998899E-4.
Is there a reason for this behaviour?

答案1

得分: 0

可以使用BigDecimal

        BigDecimal decimal1 = BigDecimal.valueOf(1.744);
        BigDecimal decimal2 = BigDecimal.valueOf(1.745);
        BigDecimal result = decimal2.subtract(decimal1);
        double diff = Math.abs(result.doubleValue());
英文:

can use BigDecimal

        BigDecimal decimal1=BigDecimal.valueOf(1.744);
        BigDecimal decimal2=BigDecimal.valueOf(1.745);
        BigDecimal result=decimal2.subtract(decimal1);
        double diff=Math.abs(result.doubleValue());

huangapple
  • 本文由 发表于 2020年6月29日 16:56:07
  • 转载请务必保留本文链接:https://java.coder-hub.com/62634564.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定