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?
The println(double) method of PrintStream Class in Java is used to print the specified double value on the stream and then break the line. This double value is taken as a parameter. Parameters: This method accepts a mandatory parameter doubleValue which is the double value to be written on the stream.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places. /* Code example to print a double to two decimal places with Java printf */ System.
Java System. out. println() is used to print an argument that is passed to it.
doubles are not exact. It is because there are infinite possible real numbers and only finite number of bits to represent these numbers.
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.
When you need precision: use BigDecimal
instead of double
.
Refer to this question for more details: Double vs. BigDecimal?
edit: if you don't need precision; you're ok with formatting the output..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With