JavaScript floating point curiosity

隐身守侯 提交于 2019-12-11 02:05:26

问题


I tried doing some floating point comparison and here is what I found:

130 === 130.000000000000014210854715 // true
130 === 130.000000000000014210854716 // false
9 === 9.0000000000000008881784197001 // true
9 === 9.0000000000000008881784197002 // false
0.1 === 0.100000000000000012490009027033 // true
0.1 === 0.100000000000000012490009027034 // false

I tried running those on Firefox and Chrome with the same results. Okay, I KNOW that floating point comparison is a bad practice and has unexpected behavior. But I just curious about those numbers, why or how does those sequence of fractional digits calculated?

If you wish you could even expand those sequence further (kind of binary searching for the next sequence).


回答1:


The fractional portion exceeds the precision of JavaScript's Number type.

JavaScript can only handle the 130.0000000000000 portion of your number, so it becomes 130 (those 0s have no significance).

Every Number in JavaScript is really a 64-bit IEEE-754 float, so the number 130.000000000000014210854715 will look like in binary...

0,10000000110,10000010000000000000000000000000000000000000000000000

Where the groups are sign (+ or -), exponent and significand/mantissa.

You can see that the number 130 is the same...

0,10000000110,10000010000000000000000000000000000000000000000000000 

You'd need a 128 bit Number for JavaScript to be able to tell these two numbers apart, ot use a bignum implementation for JavaScript.



来源:https://stackoverflow.com/questions/11339431/javascript-floating-point-curiosity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!