Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

numbersCloseEnoughToEqual function is not valid for all numbers #1549

Open
mseada94 opened this issue Nov 18, 2019 · 1 comment
Open

numbersCloseEnoughToEqual function is not valid for all numbers #1549

mseada94 opened this issue Nov 18, 2019 · 1 comment

Comments

@mseada94
Copy link

mseada94 commented Nov 18, 2019

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

@DevJSter
Copy link

DevJSter commented Aug 8, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants