// โญ๏ธ areEqualNumbers(x, y {threshold})
function areEqualNumbers(x, y, {threshold = Number.EPSILON}={}) {
return Math.abs(x - y) < threshold;
}
// โญ๏ธ a.isEqual(b, {threshold})
Number.prototype.isEqualTo = function(n, {threshold = Number.EPSILON}={}){
return areEqualNumbers(this, n, {threshold});
};
๐็ฏไพ๏ผ
const eps = Number.EPSILON; // 2^(-52) (very small)
const a = Math.pow(10, 300); // 10^300 (very big)
[
Number.EPSILON, // 2.220446049250313e-16 (2^(-52))
(0.1 + 0.2) - 0.3, // 5.551115123125783e-17
0.3 - (0.1 + 0.2), // -5.551115123125783e-17
0.1 + 0.2 === 0.3, // โ๏ธ false (should be true)
1.5 + eps > 1.5, // true
2.5 + eps === 2.5, // โ๏ธ true (should be false)
areEqualNumbers(0.1+0.2, 0.3), // true
(0.1 + 0.2).isEqualTo(0.3), // true
// big numbers
(a + 1).isEqualTo(a), // โ๏ธ true (should be false)
(a + 1) - a, // โ๏ธ 0๏ธ (should be 1)
// test threshold
(0.1).isEqualTo(0.11, {threshold: 0.05}), // true
].forEach(x => log(x));
Vector - u.isEqualTo(v)๏ผtest equality of two vectors.
JavaScript Data Structures and Algorithms (p.21)