Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not sure whether this will help clarify things, because I'm not sure what you consider to be the problem.</p> <p>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.</p> <p>Given that, I think it <strong>should</strong> round to 1.0, contradicting the question title.</p> <p>Test program:</p> <pre><code>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)); } } </code></pre> <p>Output:</p> <pre><code>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 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload