1.0.0 • Published 1 year ago

almost-compare v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

almost-compare

This package provides utility functions for comparing floating-point numbers with a default tolerance value of the floating-point epsilon.

NPM JavaScript Style Guide

Install

npm install --save almost-compare

Usage

import { almost } from "almost-compare";

const floatKeyArray = Array.from({ length: 1000 }).map(
  (_, i): KeyValue => ({ key: 0.2 + 0.1 * i - 0.1 * i, value: i })
);

const almostSortedArray = floatKeyArray.sort((a, b) => {
  return almost.compare(a.key, b.key);
});
expect(isValueStable(almostSortedArray)).toBeTruthy();
const a = 0.1;
const b = 0.2;
const expection = 0.3;

// a + b => 0.30000000000000004
expect(almost.equal(a + b, expection)).toBeTruthy();
expect(almost.less(a + b, expection)).toBeFalsy();

expect(almost.less(1, 2)).toBeTruthy();
const a = 0.1;
const b = 0.7;
const expection = 0.8;

// a + b => 0.7999999999999999
expect(almost.equal(a + b, expection)).toBeTruthy();
expect(almost.greater(a + b, expection)).toBeFalsy();

expect(almost.greater(2, 1)).toBeTruthy();
  • compare: compares two floating-point numbers and returns -1, 0, or 1 depending on whether the first number is less than, equal to, or greater than the second number.

  • greater: checks if one floating-point number is greater than another with respect to the default tolerance value.

  • less: checks if one floating-point number is less than another with respect to the default tolerance value.

  • equal: checks if two floating-point numbers are equal with respect to the default tolerance value.

License

MIT © stacew

1.0.0

1 year ago