Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing close-enough numbers in JavaScript

The following JavaScript abnormality caught me off-guard:

console.log(1 - 0.1 - 0.1 === 1 - 0.2); // true
console.log(1 - 0.2 - 0.2 === 1 - 0.4); // false

when I started testing some math, using Mocha test framework.

Is there a standard way in Mocha to compare numbers with a negligible decimal difference?

I am looking for a solution where it is possible to specify the comparison accuracy as percentage.

UPDATE

So basically I need to implement a function like this:

/**
 * @param a
 * @param b
 * @param accuracy - precision percentage.
 * @returns
 * 0, if the difference is within the accuracy.
 * -1, if a < b
 * 1, if a > b
 */
function compare(a, b, accuracy) {
}

The complexity is that accuracy is a percent value.

Examples:

compare(1.001, 1.002, 0.1) => 0
compare(12345, 12346, 0.1) => 0
like image 947
vitaly-t Avatar asked Jan 30 '26 08:01

vitaly-t


1 Answers

Mocha is a test runner / framework. It just cares about whether something throws an error or not within the test. Assertions/checks belong to assertion libraries – it's not something that Mocha takes care of / provides functionality for. You're free to use any assertion library with Mocha, like chai or unexpected. See the whole list here: https://github.com/mochajs/mocha/wiki

And from your comment, you'll probably get by with something like:

function compare(a, b, accuracy) {
  const biggest = Math.max(Math.abs(a), Math.abs(b))
  const epsilon = biggest * accuracy
  if (Math.abs(a - b) > epsilon) {
    throw(new Error("message"))
  }
}
like image 196
David da Silva Avatar answered Jan 31 '26 20:01

David da Silva