UNPKG

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