Sobes.tech
Junior — Middle

How can you check the equality of two floating-point numbers?

sobes.tech AI

Answer from AI

Due to the characteristics of representing floating-point numbers in memory, direct comparison using the == operator can be unreliable. To check the equality of two floating-point numbers, it is common to compare them with a certain acceptable error margin (epsilon). For example, in C++ you can do it like this:

#include <cmath>

bool areAlmostEqual(double a, double b, double epsilon = 1e-9) {
    return std::fabs(a - b) < epsilon;
}

Here, epsilon is the maximum allowable difference between the numbers for them to be considered equal.