Problem 44690. Comparison of floating-point numbers (doubles)
Floating-point numbers cannot generally be represented exactly, so it is usually inappropriate to test for 'equality' between two floating-point numbers. Rather, it is generally appropriate to check whether the difference between the two numbers is sufficiently small that they can be considered practically equal. (In other words, so close in value that any differences could be explained by inherent limitations of computations using floating-point numbers.)
Based on two scalar inputs of type double, namely A and B, you must return a scalar logical output set to true if the difference in magnitude between A and B is 'small', or otherwise set to false.
For this problem "small" shall be defined as no more than ten times ε, in which ε is the larger of ε₁ & ε₂, and ε₁ is the floating-point precision with which A is represented, and ε₂ is the precision with which B is represented.
EXAMPLE:
% Input A = 0 B = 1E-50
% Output practicallyEqual = false
Explanation: A is represented with a precision of ε₁ = 2⁻¹⁰⁷⁴, whereas B is represented with a precision of ε₂ = 2⁻²¹⁹. Thus ε = 2⁻²¹⁹, and the threshold is 10×2⁻²¹⁹. The difference between A and B is 1×10⁻⁵⁰, and this difference exceeds the threshold. Thus A and B are not practically equal in this example.
RELATED PROBLEMS:
Solution Stats
Problem Comments
-
2 Comments
Again, good problem, but it would be better if base-10 or base-2 was adopted as a standard at the description
Hello, Rafael. Thank-you for the feedback. Each approach has pros and cons.
Using the same base for all numbers in the problem statement would make comparison easy at a glance, but the values would not all be exact.
The mixture of bases used in the problem statement means that exact values are used for all numbers; although the reader has some inconvenience to perform a conversion in order to compare magnitudes, there may be some more educational value in that, IMHO.
—DIV
Solution Comments
Show commentsProblem Recent Solvers7
Suggested Problems
-
15768 Solvers
-
13276 Solvers
-
Swap the first and last columns
20439 Solvers
-
Project Euler: Problem 8, Find largest product in a large string of numbers
1100 Solvers
-
285 Solvers
More from this Author32
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!