As a JavaScript developer, there will be instances where you need to compare that the output of a computation is approximate to an expected value, to determine its correctness, especially when working with floating-point numbers. Working with floating-point numbers in JavaScript is can be weird, and what you expect isn’t always what you get.
To check that two numbers are approximate to each other:
const approximatelyEqual = (v1, v2, tolerance) => {
return Math.abs(v1 - v2) < tolerance;
}
The approximatelyEqual
function takes in three arguments: expected output, real output, and tolerance. The tolerance is the permissible difference between both numbers — how close you need the two numbers to be before you consider them equal enough. For example, if the difference between both numbers needs to be less than or equal to 0.001 for it to be considered correct, then 0.001 is the tolerance.
So:
approximatelyEqual(10, -10.1, 0.1)
//output: false;
approximatelyEqual(10, 10.1, 0.1)
//output: true
Blog Credits: Linda Ikechukwu
Comments are closed.