java-在控制台中输出时的浮点精度 [英] java - float precision when output in console
问题描述
float x = 0.98123452f;
System.out.println(x); //it prints out 0.9812345
float x = 0.98123453f;
System.out.println(x); //it prints out 0.98123455
我不知道为什么第二个输出是0.98123455而不是0.9812345.浮点数的精度不是7个十进制数字吗?
I have no idea why the second one's output is 0.98123455 instead of 0.9812345. Isn't the precision of float is 7 decimal digits?
推荐答案
0.98123453
是32位(符号,exp,尾数):
is 32 bits of (sign, exp, mantissa):
0 01111110 11110110011001000110000
这是:
0.9812345504760742
以双精度显示,并转换回浮点十进制表示形式:
in double precision, and cast back to float decimal representation:
0.98123455
分配给单精度(浮点数)的位数为32,而双精度则为64位.进一步请注意,经常建议BigDecimal
将您的数字存储为字符串,而不是以IEEE754格式存储.当需要对数字进行操作且精度更高时,它将进行转换.这太慢了.
The number of bits allocated to a single precision (float) is 32, and 64 bits for double precision. Further note that BigDecimal
that is frequently suggested will store your number as a string, and not in IEEE754 format. It will do a conversion when it needs to act on the number, and while it has a better precision, it is awfully slow.
编辑.为了弄清为什么打印0.98123455的原因,我们需要观察到它是数字0.98123453的最接近的单精度表示形式:
EDIT. To clarify why it prints 0.98123455, we need to observe that it is the closest single precision representation of the number 0.98123453:
00111111011110110011001000101111 = 0.9812345 (sp) = 0.9812344908714294 (dp)
00111111011110110011001000110000 = 0.98123455 (sp) = 0.9812345504760742 (dp)
00111111011110110011001000110001 = 0.9812346 (sp) = 0.981234610080719 (dp)
sp =单精度,dp =双精度
该列表是围绕数字的[-1,+ 1]二进制范围的,您可以看到0.98123453
最接近尾数的10000
后缀,而0.98123452
最接近01111
后缀.
The listing is for the [-1,+1] binary range around the number, and you can see that 0.98123453
is closest to the 10000
suffix of the mantissa, while 0.98123452
is closest to the 01111
suffix.
这篇关于java-在控制台中输出时的浮点精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!