javascript浮点运算

2017-10-11  本文已影响93人  Armin0202

问题

console.log(0.1 + 0.2)
// 0.30000000000000004
python浮点运算

引言


验证

 十进制0.1  
 => 二进制0.00011001100110011…(循环0011)   
 =>尾数为1.1001100110011001100…1100(共52位,除了小数点左边的1),指数为-4(二进制移码为00000000010),符号位为0  
 => 计算机存储为:0 00000000100 10011001100110011…11001  
 => 因为尾数最多52位,所以实际存储的值为0.00011001100110011001100110011001100110011001100110011001  
 而十进制0.2  
 => 二进制0.0011001100110011…(循环0011)  
 =>尾数为1.1001100110011001100…1100(共52位,除了小数点左边的1),指数为-3(二进制移码为00000000011),符号位为0  
 => 存储为:0 00000000011 10011001100110011…11001  
 因为尾数最多52位,所以实际存储的值为0.00110011001100110011001100110011001100110011001100110011  
 那么两者相加得:      
 0.00011001100110011001100110011001100110011001100110011001  
+  0.00110011001100110011001100110011001100110011001100110011 (确认??)  
 =  0.01001100110011001100110011001100110011001100110011001100  
 转换成10进制之后得到:0.30000000000000004   
console.log('0.00011001100110011001100110011001100110011001100110011001'.split('.')[1].length)
// 56

参考

十进制小数转换为二进制小数
0.1+0.2!=0.3, why? how to solve? -- 简议javascript的浮点运算
彻底理解0.1 + 0.2 === 0.30000000000000004的背后


上一篇下一篇

猜你喜欢

热点阅读