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 } // use "==" operator, handles infinities
15
16
17 if (x.eq(y)) {
18 return true;
19 } // NaN
20
21
22 if (x.isNaN() || y.isNaN()) {
23 return false;
24 } // at this point x and y should be finite
25
26
27 if (x.isFinite() && y.isFinite()) {
28 // check numbers are very close, needed when comparing numbers near zero
29 var diff = x.minus(y).abs();
30
31 if (diff.isZero()) {
32 return true;
33 } else {
34 // use relative error
35 var max = x.constructor.max(x.abs(), y.abs());
36 return diff.lte(max.times(epsilon));
37 }
38 } // Infinite and Number or negative Infinite and positive Infinite cases
39
40
41 return false;
42}
\No newline at end of file