简体   繁体   English

如何安全地比较 std::complex<double> 零和一些精度 Epsilon? </double>

[英]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.我将值除以a并且不想得到INF作为结果。

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.您可以将其与值为 0 的浮点文字进行比较。您不能使用 integer 文字。 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".例如, epsilon不一定是“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.您可能会考虑的另一件事是您是否应该将std::abs(a)与阈值进行比较,而不是分别比较组件,即是否应该使用欧几里德距离而不是曼哈顿距离。

Have you tried std::fpclassify from <cmath> ?您是否尝试过来自<cmath>std::fpclassify

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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