{AGUT2} {H}-IWIK <al********************@ambtinternet.com> wrote in message news:<op**************@mercury.nildram.net>...
I have got an
if ( fabs(double1-double2) < 0.0000001 )
{
...
}
In my program and this seems to work wonderfully.
Note however that this is not the general rule. Consider the problem
where you have the typical magnitude of values inferior to 0.0000001,
then all your values will seem equal according to that rule.
A more general solution would be to consider the magnitude of the
numbers involved in the comparison:
#include <iostream>
bool equals(double d1, double d2, double precision);
int main()
{
double a = 1, b = 1.0001;
if (equals(a, b, 0.00001))
std::cout << "equals" << std::endl;
else
std::cout << "differs" << std::endl;
return 0;
}
bool equals(double d1, double d2, double precision)
{
double eps1 = fabs(d1), eps2 = fabs(d2), eps;
eps = (eps1 > eps2) ? eps1 : eps2;
if (eps == 0.0)
return true; //both numbers are 0.0
//eps hold the minimum distance between the values
//that will be considered as the numbers are equal
//considering the magnitude of the numbers
eps *= precision;
return (fabs(d1 - d2) < eps);
}