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
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"))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With