Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How java stores float v double

I realize a decimal number can only be so precise stored as a float in a binary system but what I don't understand is what is happening at the 7 decimal place in my output of 10/7.

In my first output test I noticed that the 5 (7th place) at the end of the float v the 4 (7th place) followed by a 2 in the double. I would think the 7th place in the float would be a 4 since the 8th place in the double is a 2.

Float 1.4285715 Double 1.4285714285714286

I then ran the next output test using the float format to 17 places. The 8th place in each is different - the float is a 6 which is why the 7th place is rounded to 5 I assume.

Float 1.428571462631225600 Double 1.428571428571428600

In the third output test I tried a direct cast with the string format to see what would happen. I got the same results as the second test.

If I have a simplistic question to a complex floating point storage method - I do apologize.

    float f = 10/7f;
    double d = 10/7d;

    System.out.format
        ("Float  %1s\nDouble %2s\n", f,d);
    /*
     *  Float  1.4285715
        Double 1.4285714285714286
     */

    System.out.format
        ("Float  %1$.17f\nDouble %2$.17f\n", f,d);
    /*
     *  Float  1.428571462631225600
        Double 1.428571428571428600
     */

    System.out.format
        ("Float  %1s\nDouble %2s\n", (double)f,d);
    /*
     *  Float  1.4285714626312256
        Double 1.4285714285714286
     */
like image 978
user1178761 Avatar asked Jan 30 '12 19:01

user1178761


2 Answers

In my first output test I noticed that the 5 (7th place) at the end of the float v the 4 (7th place) followed by a 2 in the double. I would think the 7th place in the float would be a 4 since the 8th place in the double is a 2.

This expectation only makes sense if you think that floats are stored internally in decimal and rounded to some number of decimal digits. But this is not true, floats are stored internally in binary and rounded to some number of binary digits.

Your expectations are based on a misunderstanding of how floating point numbers are stored. You see doubles having more accurate decimal places only because this is consequence of them having more accurate binary places. The implementation does not store the numbers in a decimal form at all.

like image 117
David Schwartz Avatar answered Sep 21 '22 22:09

David Schwartz


Java uses IEEE-754 for representing floating point numbers. You can read more about the IEEE-754 standard in many places.

like image 33
maerics Avatar answered Sep 19 '22 22:09

maerics