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?
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?