java中的浮点数和双精度数有多少位有效数字?

2022-01-09 00:00:00 floating-point java

浮点数有 32 位二进制数,双精度数有 64 位二进制数吗?文档太难理解了.

Does a float have 32 binary digits and a double have 64 binary digits? The documentation was too hard to make sense of.

所有位都转换为有效数字吗?还是小数点的位置占用了一些位?

Do all of the bits translate to significant digits? Or does the location of the decimal point take up some of the bits?

推荐答案

float: 32 bits (4 bytes) 其中23 bits用于尾数(大约 7 个十进制数字).8 位用于指数,因此浮点数可以使用这 8 位将小数点向右或向左移动".这样做可以避免在尾数中存储大量零,如 0.0000003 (3 × 10-7) 或 3000000 (3 × 107).有 1 位用作符号位.

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can "move" the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.

double:64 位(8 字节),其中 52 位 用于尾数(大约 16 位十进制数字).11位用于指数,1位为符号位.

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

由于我们使用二进制(只有 0 和 1),所以当数字非零时,尾数中的一位隐含为 1(浮点数和双精度数都使用此技巧).

Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.

此外,由于所有内容都是二进制(尾数和指数),因此转换为十进制数通常不准确.像 0.5、0.25、0.75、0.125 这样的数字被精确存储,但 0.1 不是.正如其他人所说,如果您需要精确存储美分,请不要使用 float 或 double,使用 int、long、BigInteger 或 BigDecimal.

Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.

来源:

http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers

http://en.wikipedia.org/wiki/Binary64

http://en.wikipedia.org/wiki/Binary32

相关文章