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

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

推荐答案

浮动: 32位(4字节),其中 23位用于尾数(约7个十进制数字).指数使用8位,因此浮点数可以使用这8位将小数点移动"到右侧或左侧.这样做可以避免在尾数中存储大量零,例如0.0000003(3×10 -7 )或3000000(3×10 7 ).有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.

双精度: 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.正如其他人所说,如果您需要精确存储美分,请不要使用浮点数或双精度数,而应使用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天全站免登陆