You-Dont-Know-JS
You-Dont-Know-JS copied to clipboard
numbersCloseEnoughToEqual function is not valid for all numbers
numbersCloseEnoughToEqual
function is not valid for all numbers.
Try this example
numbersCloseEnoughToEqual(2.02 + 1.135, 3.155); // false
Please see snippit in the end of this commet https://stackoverflow.com/a/56967003
If the numbersCloseEnoughToEqual function is not working as expected, it might be due to the limitations of floating-point arithmetic. Floating-point numbers in computers are represented using a finite number of binary digits, which can lead to rounding errors when performing arithmetic operations, especially with numbers that cannot be represented exactly in binary.
The example you've provided (2.02 + 1.135 not being equal to 3.155) is a classic illustration of the limitations of floating-point arithmetic. Even though mathematically these two expressions should be equal, due to the way floating-point numbers are represented in binary, the result might not be exactly 3.155.
To compare floating-point numbers for "closeness" or "equality," it's often recommended to use a tolerance threshold. You can modify the numbersCloseEnoughToEqual
function to compare if the absolute difference between the two numbers is within a small tolerance value. For example:
javascript
return Math.abs(a - b) < tolerance;
}
console.log(numbersCloseEnoughToEqual(2.02 + 1.135, 3.155)); // true
By introducing a tolerance value, you acknowledge the inherent imprecision of floating-point arithmetic and allow for a small difference between the numbers while still considering them as "close enough" to be considered equal.
Remember that working with floating-point numbers requires careful consideration of rounding errors and precision issues, and using tolerance-based comparisons is a common approach to handle these situations.