nearlyEqual.js 1.2 KB

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