Search code examples
c++performancecomparison

Absolute integer values comparing and squared values comparing. Is it equivalent?


There is the standard way to compare the absolute values of two integers:

if (std::abs(a) > std::abs(b))
{
   // code
}

Sometimes I meet another way of absolute values comparing based on values squaring:

if (a * a > b * b)
{
   // code
}

Are these methods equivalent? Is there a difference in the performance of these methods? Which method would you prefer?


Solution

  • Until the integer product overflows, the two methods will behave equivalently. I would prefer using std::abs() because that more clearly states my intentions- to compare the magnitude of two numbers. If I use the product a * a, any other maintainers that read by code will wonder what a * a signifies.

    While beyond the scope of the literal question, I feel its important to emphasize that these two methods diverge much faster for non-integer types. For floating point, you'll run into rounding errors very quickly, resulting in slightly different comparisons, which may sometimes give the wrong result (one may argue you shouldn't do direct floating point comparisons anyways, and instead clamp to a range, but still).

    More subtlety, comparison of complex values in this manner will be incorrect. The typical calculation of the absolute value for a complex number a + bi is sqrt(a^2 + b^2) where ^ denotes exponentiation. However, (a + bi)^2 will yield a^2-b^2 + 2abi, which cannot ever be equal for non-zero a and b.