6

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
     */
4

4 回答 4

7

在我的第一个输出测试中,我注意到浮点数末尾的 5(第 7 位)v 4(第 7 位),然后是双精度数中的 2。我认为浮动中的第 7 位是 4,因为双打中的第 8 位是 2。

只有当您认为浮点数在内部以十进制存储并四舍五入到一定数量的十进制数字时,这种期望才有意义。但这不是真的,浮点数在内部以二进制形式存储并四舍五入到一定数量的二进制数字。

您的期望是基于对浮点数存储方式的误解。您看到双精度数具有更准确的小数位只是因为这是它们具有更准确的二进制位的结果。该实现根本不以十进制形式存储数字。

于 2012-01-30T20:12:00.183 回答
3

Java 使用 IEEE-754 来表示浮点数。您可以在许多地方阅读有关IEEE-754 标准的更多信息。

于 2012-01-30T19:53:23.790 回答
2

有关简化说明,请尝试此站点:

http://floating-point-gui.de/basic/

有关非常详细的解释,请尝试以下操作:

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

于 2012-01-30T19:55:02.703 回答
1

看来,当您使用 a 时float,它使用该数字的默认精度为 8 位。当您指定精度时,它会清楚地表明它实际用于double计算值。

于 2012-01-30T19:55:42.577 回答