Reputation: 5741
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;
}
Upvotes: 2
Views: 479
Reputation: 23793
I guess that you have a typo in isEqual
, you want :
double epsilon = 1 / pow(10.0, decimals);
Or
double epsilon = pow(10.0, -decimals);
So your espilon will be 10^-(digits)
As commented, your current function returns true for any number whose difference is less than 10^digits
...
Notes :
std::numeric_limits<double>::epsilon()
Upvotes: 3