简体   繁体   中英

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.

I need to check is my complex number a zero. How can I do it for floating point numbers?

You can compare it with a floating point literal with value of 0. You cannot use an integer literal. Example:

a == 0.0

Can I use something like...

What you've shown doesn't compare whether the complex number is zero; it compares whether the complex number is near zero.

Whether that is a good way to compare if the number is near zero depends on use case. For example, epsilon is not necessarily the best threshold of "near". Another thing that you might consider is whether you should compare std::abs(a) to the threshold instead of comparing the components separately ie whether you should use euclidean distance instead of manhattan distance.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM