JavaScript浮点好奇心 [英] JavaScript floating point curiosity
问题描述
我尝试做一些浮点比较,这里是我发现:
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
我试过在Firefox和Chrome上运行相同的结果。好吧,我知道浮点比较是一个坏的做法,有意想不到的行为。但我只是好奇那些数字,为什么或如何计算这些序列的小数位数?
如果你希望你甚至可以进一步扩展这些序列下一个序列)。
小数部分超出JavaScript的 Number
类型的精度。 / p>
JavaScript只能处理您的号码的 130.0000000000000
部分,因此变为 code>(
0
没有意义)。
每
在JavaScript中实际上是一个64位的 IEEE-754 浮动广告,因此 130.000000000000014210854715
将看起来像二进制...
1000000011010000010000000000000000000000000000000000000000000000
群组符号( + $ c $
您可以看到数字<$ c $或$ c> 130
是相同的...
0,10000000110,1000001000000000000000000000000000000000000000000
您需要一个128位的 Number
要区分这两个数字,请使用 bignum JavaScript的实现。
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).
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 0
s 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.
这篇关于JavaScript浮点好奇心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!