justmyfreak
justmyfreak

Reputation: 1270

Strange loop on Java for 0.1 to 2

I tried to loop from 0.1 to 2.0 and then print the output to the console.. But I got strange output like these:

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
1.2
1.3
1.4000000000000001
1.5000000000000002
1.6000000000000003
1.7000000000000004
1.8000000000000005
1.9000000000000006
2.0000000000000004

Source code:

public class test {
    public static void main(String[] a) {
        double i = 0.1;
        while (i < 2.1)
            System.out.println(i);
            i+=0.1;
        }
    }
}

Why it doesn't this print the exact numbers instead of having point like 0.79999999999? Also is ther any difference using for instead of while, since I dont know how to make 0.1 increment?

Upvotes: 0

Views: 1074

Answers (2)

Glen P
Glen P

Reputation: 709

That's a bug (on your side).

Do not use floating point numbers until you learn what they are and how they work.

Upvotes: 0

geekosaur
geekosaur

Reputation: 61379

This is normal. It's inherent in floating point; numbers like 0.3 can't be stored as exact values in binary, so you get slowly accumulating errors. References: Python manual, Wikipedia, Technical explanation from Princeton CS.

Upvotes: 4

Related Questions