[英]comparison of two doubles for positive and negative
I would like to compare two doubles with negative values.I have no problem if they are both positive. 我想比较两个带有负值的双打,如果它们都是正的,我没有问题。 However, I can't figure out if one of the values is negative.
但是,我不知道其中一个值是否为负。 This is I've done.
这已经完成了。
#include <iostream>
const double PI = 3.14159265358979323846;
bool isEqual(double a, double b, int decimals)
{
double epsilon = pow(10.0, decimals);
if( fabs( a - b) < epsilon)
return true;
return false;
}
int main()
{
double Theta;
Theta = 3.1415;
if ( isEqual(Theta, -PI, 10) )
{
std::cout << "Theta == -PI " << Theta << " == " << -PI << std::endl;
}
Theta = -3.1415;
if ( isEqual(Theta, -PI, 10) )
{
std::cout << "Theta == -PI " << Theta << " == " << -PI << std::endl;
}
std::cin.get();
return 0;
}
I guess that you have a typo in isEqual
, you want : 我想您在
isEqual
有一个错字,您想要:
double epsilon = 1 / pow(10.0, decimals);
Or 要么
double epsilon = pow(10.0, -decimals);
So your espilon will be 10^-(digits)
因此,您的espilon为
10^-(digits)
As commented, your current function returns true for any number whose difference is less than 10^digits
... 如前所述,您的当前函数对于差小于
10^digits
任何数字都返回true ...
Notes : 注意事项:
std::numeric_limits<double>::epsilon()
std::numeric_limits<double>::epsilon()
获取epsilon。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.