java float 向double 隐式转换精度丢失
天蓬老师
天蓬老师 2017-04-18 09:18:28
0
2
847

java float 向double 隐式转换精度会有丢失

    float f = 8.69f;
    int a = Float.floatToIntBits(f);
    String floatStr = Integer.toBinaryString(a);

    double d1 = f;
    long b = Double.doubleToLongBits(d1);
    String convertStr = Long.toBinaryString(b);

    double d2 = 8.69d;
    long c = Double.doubleToLongBits(d2);
    String doubleStr = Long.toBinaryString(c);

    System.out.println(floatStr);
    System.out.println(convertStr);
    System.out.println(doubleStr);

输出为
1000001000010110000101000111101 100000000100001011000010100011110100000000000000000000000000000 100000000100001011000010100011110101110000101000111101011100001

想问下,为什么在隐式转换的过程中,jvm只是单纯的拷贝float中的尾数部分,然后补0,而不是精确的计算尾数部分的值?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
左手右手慢动作

There is no loss of precision when adding 0 to the mantissa, this is how floating point numbers are represented

洪涛

float occupies 4 bytes, while double occupies 8 bytes.
During the memory copy process, only 4 bytes are copied in, and the remaining bytes default to 0. (This is not necessarily the case in release mode and debug mode.)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!