🔢Number.EPSILON

🚧 under construction

JSvalueprimitivenumberspecial ⟩ Number.EPSILON

Number.EPSILON = 2¯⁵² ≈ 2.2 * 10¯¹⁶ (就是在 2⁰ ~ 2¹ 這個區間內,每個可以表示的數字之間的間隔)

const {log} = console;

/*
    ┌─────────────────────────────────────┐
    │ Number.EPSILON = 2¯⁵² ≈ 2.2 * 10¯¹⁶ │
    └─────────────────────────────────────┘

    0.1 + 0.2 === 0.3 ?

 2¯⁴↴                                                   ┌┐ (11 進位?)
    110011001100110011001100110011001100110011001100110011....  (math)
    11001100110011001100110011001100110011001100110011010 = 0.1 (JS)
     ╰──────────────────── 52-bit ──────────────────────╯

2¯³↴                                                   ┌┐ (11 進位?)
   110011001100110011001100110011001100110011001100110011....   (math)
   11001100110011001100110011001100110011001100110011010  = 0.2 (JS)
    ╰──────────────────── 52-bit ──────────────────────╯

2¯³↴11001100110011001100110011001100110011001100110011010 = 0.1 (JS)
 + 11001100110011001100110011001100110011001100110011010  = 0.2 (JS)
─────────────────────────────────────────────────────────────────────
                                                      ┌┐ (11 進位?)
  1001100110011001100110011001100110011001100110011001110
  10011001100110011001100110011001100110011001100110100   = 0.1 + 0.2
─────────────────────────────────────────────────────────────────────
  10011001100110011001100110011001100110011001100110011   = 0.3 (JS)
  ⇧╰──────────────────── 52-bit ──────────────────────╯
  2¯²                                                 ↳ 2¯⁵⁴

  (0.1 + 0.2) - 0.3 = 1 * 2¯⁵⁴ = 5.551115123125783e-17

*/

// isEqual(a,b)
function isEqual(a, b){
    // |a-b| < ε
    return Math.abs(a - b) < Number.EPSILON;
}

// number.isEqual(a)
Number.prototype.isEqual = function(n){
    return isEqual(this, n);
}

// --------------- log ---------------

[
    0.1 + 0.2 === 0.3,          // false❗️
    (0.1 + 0.2) - 0.3,          // 5.551115123125783e-17

    isEqual(0.1 + 0.2, 0.3),    // true
    (0.1 + 0.2).isEqual(0.3),   // true

].forEach(x => log(x))

Last updated