Printing Java doubles to System.out in Java

double, java

Solution

What you have here is floating point inaccuracy. Because `double`s have limited precision they cannot precisely represent all decimal numbers. In particular `0.1` is a recurring binary so all finite length binary representations will be inaccurate. This means the computer cannot store the numbers you're using exactly.

You can fix your output by formatting it (e.g. `System.out.format("%d. x=%.1f", i, a);`) or you can fix your numbers by using `BigDecimal` instead of `double`. Alternatively you could reduce the scale of the problem by calculating `a` each time rather than accumulating (and adding an incremental error each time), e.g. `a = i/10.0`. It depends on what you are trying to achieve.

The important "take home message" is that doubles cannot be relied on to give complete accurate answers and you should expect small errors in floating point arithmetic.

Problem

This code isn't working as I thought it would. ``` a=-1; b=0.1; for(i=0;i<=20;i++){ System.out.println(i + ". x= " + a); a=a+b; } ``` On the console I should see: ``` 0. x= -1.0 1. x= -0.9 2. x= -0.8 3. x= -0.7 4. x= -0.6 5. x= -0.5 6. x= -0.4 7. x= -0.3 ``` ...etc But this is what happens: ``` 0. x= -1.0 1. x= -0.9 2. x= -0.8 3. x= -0.7000000000000001 4. x= -0.6000000000000001 5. x= -0.5000000000000001 6. x= -0.40000000000000013 7. x= -0.30000000000000016 8. x= -0.20000000000000015 9. x= -0.10000000000000014 10. x= -1.3877787807814457E-16 11. x= 0.09999999999999987 12. x= 0.19999999999999987 13. x= 0.2999999999999999 14. x= 0.3999999999999999 15. x= 0.4999999999999999 16. x= 0.5999999999999999 17. x= 0.6999999999999998 18. x= 0.7999999999999998 19. x= 0.8999999999999998 20. x= 0.9999999999999998 ``` What am I doing wrong here?

Original source

Related problems