java中浮点数和双精度数有多少个有效数字? [英] How many significant digits do floats and doubles have in java?

查看:31
本文介绍了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

这篇关于java中浮点数和双精度数有多少个有效数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆