nearlyEqual.js 1.3 KB

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