一、概述
正整数直接按照源码存储,负整数按照补码存储,那么小数如何存储表示?
二、浮点数的概念(IEEE754)
浮点数是计算机中用于表示实数的一种方法,类似于科学计数法,如:
- 314.4=3.144x102
- 0.00314=3.14x10-3
- 255=2.55x102
由于电脑存储2进制长度有限,这种方法仅能近似的表示某个数。
Java中存放浮点数遵守的标准是IEEE754。
三、IEEE754标准
其定义如何用2进制来存储浮点数,根据公式:
V=(-1)N x M x 2R
其中:
- N=为符号位,N=1,则为负数;N=0,则为整数
- M=底数(尾数)
- R=幂(指数)
三部分(NMR)分开存储,有两种方案。
(一)、单精度(32位)
? 1(符号位)+8(指数)+23(底数),N-(R+127)-M
![][1]
(二)、双精度(64位)
1(符号位)+11(指数)+52(底数),N-(R+1023)-M
![][2]
(三)、特殊值
- 无穷 : 指数全为1,底数全为0
0 11111111 000000000000....0000
1 11111111 000000000000....0000
- NaN(not a number) : 指数全为1,底数不全为0
0 1111111 101010010...0000
1 1111111 101010000...0000
四、如何存储(如3.14)
(一)、把小数转换为2进制
3.14=0b11.0010001111010111...
(二)、转换为公式格式,底数部分小数点前为1
V=(-1)^N x M x 2^R
0b11.0010001111010111...
=(-1)0 x 1.10010001111010111... x 21
(三)、符号位N计算
正数为0,负数为1
3.14为正,N=0
(四)、指数部分R计算
R=1
指数部分R要加上127,转换为2进制(无符号)
指数1 加上127(1+127)=128
=0b1000 0000
R=0b1000 0000
(五)、底数部分M计算
去掉小数点前面的1,把剩余的序列拼接即可(如何位数超过范围,会进行四舍五入)
1.10010001111010111...=(丢掉1,这样可以多表示一位数)
M=10010001111010111...
(六)、6)组合起来
3.14=N-R-M
3.14=0b0_10000000_10010001111010111000011
五、总结
- 浮点数不能准确表示小数
- 单精度最大值约是3.40E38,最小值(1.40E-45)
- 双精度最大值约是1.79E308,最小值(4.94E-324)
- 浮点数如何存储了解即可
[1]:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmoAAAB9CAMAAAAlQL9HAAAAGXRFWHRTb2Z0d2FyZQB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