Click to See Complete Forum and Search --> : how to compare to float number?


fantasy2004
December 6th, 2005, 11:13 AM
Hi, all

I have a question about how to compare two float.
the follows is my code
template < class T >
class MyPoint
{
public:
typedef typename MyPoint<T> Point;
public:
Point(T x,T y) { this->x = x; this->y = y; };
friend bool operator < ( const Point & left, const Point & right )
{
if ( left.x != right.x )
{
return ( left.x < right.x );
}
else
{
return ( left.y < right.y );
}
}
public:
T x,y;
};
int main()
{
typedef MyPoint<float> POINT;

set < POINT > point;
point.insert( POINT(1.0,1.0) );
point.insert( POINT(0.0,0.0) );


set < POINT > :: iterator it;

it = point.find( POINT(1.00000005,1.0) );
if ( it == point.end() )
{
cout << "not found\n";
}
else
{
cout << it->x<< " " << it->y << "\n";
}
return 0;
}


I found that POINT(1.00000005,1.0) is the equal to POINT(1.0,1.0) ,
but some times I want to get the result POINT(1.000001,1.0) == POINT(1.0,1.0) be true.

what is the better way to do this?

Rigel
December 6th, 2005, 11:19 AM
There isn't a way to accurately represent floating point numbers in binary.

Here is a good way to compare floating point numbers.

http://www.codeguru.com/forum/showthread.php?t=323835

fantasy2004
December 6th, 2005, 11:49 AM
thank you Rigel for so quickly reply!

the link that you provide is very helpful.

but I hope to set the two point equal according to some given numerical error.

I change the MyPoint class like follows:
template < class T >
class MyPoint
{
public:
typedef typename MyPoint<T> Point;
public:
Point(T x,T y) { this->x = x; this->y = y; };
friend bool operator < ( const Point & left, const Point & right )
{
double eps = 1.0e-5;
double dx,dy;
dx = abs( left.x - right.x );
dy = abs( left.y - right.y );
double maxx = max( abs(left.x), abs(right.x) ) + 1.0e-30;
double maxy = max( abs(left.y), abs(right.y) ) + 1.0e-30;

if ( !( ( dx < eps ) || ( dx / maxx < eps ) ) )
{
return ( left.x < right.x );
}
else if ( !( ( dy < eps ) || ( dy/maxy < eps ) ) )
{
return ( left.y < right.y );
}
else
{
return false;
}
}
public:
T x,y;
};

but i have to set the eps in function operator <
I hope i can set the error eps without change the codes.