Can someone explain this phenomenon?

Maximilian

Lifer
Feb 8, 2004
12,604
15
81
Code:
public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        for(double aDouble = -1.0; aDouble <= 1.0; aDouble = aDouble + 0.1)
        {
            System.out.println(aDouble);
        }
        
    }
    
}

Output:
Code:
-1.0
-0.9
-0.8
-0.7000000000000001
-0.6000000000000001
-0.5000000000000001
-0.40000000000000013
-0.30000000000000016
-0.20000000000000015
-0.10000000000000014
-1.3877787807814457E-16
0.09999999999999987
0.19999999999999987
0.2999999999999999
0.3999999999999999
0.4999999999999999
0.5999999999999999
0.6999999999999998
0.7999999999999998
0.8999999999999998
0.9999999999999998

o_O:confused: float does it as well.
 
Last edited:

mv2devnull

Golden Member
Apr 13, 2010
1,526
160
106
Floating point values have limited precision.
http://en.wikipedia.org/wiki/Floating_point

Limited precision means that you can only have discrete values. Apparently, -0.7 is not one of them, so the result of -0.8+0.1 has the nearest possible value.

If you limit the number of digits that the println does show, then println will round and you will not know that the "-0.7" you will see is not what aDouble actually holds.
 

Cogman

Lifer
Sep 19, 2000
10,286
145
106
It comes down to how floating points are represented and the fact that it is base 2.

Imagine you want to represent 0.125. In base ten we could say that is 1/10 + 2/100 + 5/1000

The same concept is applied with floats, only the denominator is base 2 so we would have the problem of

0.125 = x/2 + y/4 + z/8 + i/16 + j/32

or

0.125 = 0/2 + 0/4 + 1/8 + 0/16 + 0/32

Because of this. Certain numbers can't be represented 0.1 is one of them. It is a repeating number (like 1/3).

So in the end, the compiler and the language does its best bet. It is the same problem

1/3 + 1/3 + 1/3 = 1, right?

Yet if we truncate it we would end up with something like

0.33333333333 + 0.33333333333 + 0.33333333333 = 0.99999999999


see This wiki article for more examples
 

Childs

Lifer
Jul 9, 2000
11,313
7
81
Isn't -1.3877787807814457E-16 what he is asking about? Shouldn't it be something like -0.000000000000000nn?
 
Last edited: