Search code examples
c++floating-pointcomparisonsimilaritycomplex-numbers

How to safely compare std::complex<double> with Zero with some precision Epsilon?


I need to safely check is my complex number a zero (or very similar to it). How can I do it for floating point numbers?

Can I use something like:

std::complex<double> a;
if(std::abs(std::real(a)) <= std::numerical_limits<double>::epsilon() && std::abs(std::imag(a)) <= std::numerical_limits<double>::epsilon())
{
//...
}

I will divide values by a and don't want to get the INF as result.


Solution

  • Have you tried std::fpclassify from <cmath>?

    if (std::fpclassify(a.real()) == FP_ZERO) {}
    

    To check if both the real and imaginary part of a complex are 0:

    if (a == 0.0) {}
    

    As mentioned by @eerorika a long time before I did. An answer you rejected.
    Floating point precision, rounding, flag raising, subnormal is all implementation-defined (See: [basic.fundamental], [support.limits.general], and ISO C 5.2.4.2.2).