UNPKG

mathjs

Version:

Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with dif

42 lines (37 loc) 1.25 kB
/** * Compares two BigNumbers. * @param {BigNumber} x First value to compare * @param {BigNumber} y Second value to compare * @param {number} [epsilon] The maximum relative difference between x and y * If epsilon is undefined or null, the function will * test whether x and y are exactly equal. * @return {boolean} whether the two numbers are nearly equal */ export function nearlyEqual (x, y, epsilon) { // if epsilon is null or undefined, test whether x and y are exactly equal if (epsilon === null || epsilon === undefined) { return x.eq(y) } // use "==" operator, handles infinities if (x.eq(y)) { return true } // NaN if (x.isNaN() || y.isNaN()) { return false } // at this point x and y should be finite if (x.isFinite() && y.isFinite()) { // check numbers are very close, needed when comparing numbers near zero const diff = x.minus(y).abs() if (diff.isZero()) { return true } else { // use relative error const max = x.constructor.max(x.abs(), y.abs()) return diff.lte(max.times(epsilon)) } } // Infinite and Number or negative Infinite and positive Infinite cases return false }