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

查看:135
本文介绍了在Java中有多少有效数字有浮点数和双精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个浮点数是否有32个二进制数字,而一个double是否有64个二进制数字?文档太难以理解了。



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

strong> 32位(4个字节),其中 23位用于尾数(约7位十进制数字)。 8位用于指数,所以浮点数可以使用这8位将小数点移动到右侧或左侧。这样做避免了在0.0000003(3×10 -7 -7)或3000000(3×10 7 7)中存储大量的零。有一位用作符号位。



double 64位(8字节)其中 52位用于尾数(大约16位十进制数字)。由于我们使用的是二进制(只有0和1),所以尾数中的一位隐含地为1(即1位是符号位)。 (float和double使用这个技巧)当数字是非零。

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



来源:



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

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


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


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) 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 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.

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.

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.

Sources:

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天全站免登陆