java 3 0.1,在java中添加1/3会导致1.0,而不应该

Note: question still not answered thoroughly! This questions does not deal with the issue of truncation of floating point parts!!!

In Java I have this simple code:

double sum = 0.0;

for(int i = 1; i <= n; i++){

sum += 1.0/n

}

System.out.println("Sum should be: 1");

System.out.println("The result is: " + sum);

Where n can be any integer. For numbers like 7,9, the expected value for sum is to have difference in the last digits of sum, and the result is 0.999999999998 or something but the output when I use 3 is 1.0.

If you add 1/3 3 times, you would expect a number close to 1, but I get exactly 1.0.

Why?

解决方案

I'm not sure whether this will help clarify things, because I'm not sure what you consider to be the problem.

Here is a test program that uses BigDecimal, as previously suggested, to display the values of the intermediate answers. At the final step, adding the third copy of 1.0/3 to the sum of two copies, the exact answer is half way between 1.0 and the next double lower than it. In that situation the round-to-even rounding rule picks 1.0.

Given that, I think it should round to 1.0, contradicting the question title.

Test program:

import java.math.BigDecimal;

public class Test {

public static void main(String[] args) {

final double oneThirdD = 1.0/3;

final BigDecimal oneThirdBD = new BigDecimal(oneThirdD);

final double twoThirdsD = oneThirdD + oneThirdD;

final BigDecimal twoThirdsBD = new BigDecimal(twoThirdsD);

final BigDecimal exact = twoThirdsBD.add(oneThirdBD);

final double nextLowerD = Math.nextAfter(1.0, 0);

final BigDecimal nextLowerBD = new BigDecimal(nextLowerD);

System.out.println("1.0/3: "+oneThirdBD);

System.out.println("1.0/3+1.0/3: "+twoThirdsBD);

System.out.println("Exact sum: "+exact);

System.out.println("Rounding error rounding up to 1.0: "+BigDecimal.ONE.subtract(exact));

System.out.println("Largest double that is less than 1.0: "+nextLowerBD);

System.out.println("Rounding error rounding down to next lower double: "+exact.subtract(nextLowerBD));

}

}

Output:

1.0/3: 0.333333333333333314829616256247390992939472198486328125

1.0/3+1.0/3: 0.66666666666666662965923251249478198587894439697265625

Exact sum: 0.999999999999999944488848768742172978818416595458984375

Rounding error rounding up to 1.0: 5.5511151231257827021181583404541015625E-17

Largest double that is less than 1.0: 0.99999999999999988897769753748434595763683319091796875

Rounding error rounding down to next lower double: 5.5511151231257827021181583404541015625E-17

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值