3

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

4

1 に答える 1

3

小数部分が JavaScript のNumber型の精度を超えています。

130.0000000000000JavaScript は数値の一部しか処理できないため、 130(これら0は意味がありません) になります。

JavaScript のEveryNumberは実際には 64 ビットのIEEE-754 float であるため、数値130.000000000000014210854715は 2 進数のようになります...

0,10000000110,10000010000000000000000000000000000000000000000000000

グループは符号 (+または-)、指数、および仮数/仮数です。

130番号が同じであることがわかります...

0,10000000110,10000010000000000000000000000000000000000000000000000 

NumberJavaScript がこれら 2 つの数値を区別できるようにするには、128 ビットが必要です。JavaScriptまたはbignumにfloat128実装を使用する必要はありません。

于 2012-07-05T07:17:38.740 に答える