nearlyEqual.js (1359B)
1 "use strict"; 2 3 Object.defineProperty(exports, "__esModule", { 4 value: true 5 }); 6 exports.nearlyEqual = nearlyEqual; 7 8 /** 9 * Compares two BigNumbers. 10 * @param {BigNumber} x First value to compare 11 * @param {BigNumber} y Second value to compare 12 * @param {number} [epsilon] The maximum relative difference between x and y 13 * If epsilon is undefined or null, the function will 14 * test whether x and y are exactly equal. 15 * @return {boolean} whether the two numbers are nearly equal 16 */ 17 function nearlyEqual(x, y, epsilon) { 18 // if epsilon is null or undefined, test whether x and y are exactly equal 19 if (epsilon === null || epsilon === undefined) { 20 return x.eq(y); 21 } // use "==" operator, handles infinities 22 23 24 if (x.eq(y)) { 25 return true; 26 } // NaN 27 28 29 if (x.isNaN() || y.isNaN()) { 30 return false; 31 } // at this point x and y should be finite 32 33 34 if (x.isFinite() && y.isFinite()) { 35 // check numbers are very close, needed when comparing numbers near zero 36 var diff = x.minus(y).abs(); 37 38 if (diff.isZero()) { 39 return true; 40 } else { 41 // use relative error 42 var max = x.constructor.max(x.abs(), y.abs()); 43 return diff.lte(max.times(epsilon)); 44 } 45 } // Infinite and Number or negative Infinite and positive Infinite cases 46 47 48 return false; 49 }