Junior — Middle
What methods can be used to determine the equality of two floating-point numbers in programming?
sobes.tech AI
Answer from AI
Comparing floating-point numbers directly with == is often unreliable due to the way numbers are represented in memory (rounding errors).
Main methods for determining equality:
- Comparison using delta (epsilon) — checks if the absolute difference between the numbers is less than a small value:
const double EPSILON = 1e-9;
if (fabs(a - b) < EPSILON) {
// consider a and b equal
}
- Relative comparison — considers the scale of the numbers, useful when numbers can be very large or small:
double diff = fabs(a - b);
double largest = fmax(fabs(a), fabs(b));
if (diff <= largest * EPSILON) {
// consider equal
}
- Using specialized functions or libraries that account for the peculiarities of floating-point numbers.
The choice of method depends on the context of the problem and the required precision.