G
G Patel
Hello,
I'm having trouble with floating point problems.
I'm trying to write a function that calculates the distance between two
cartesian points (integer coordinates). I have the function working,
but it fails on one test case.
Here is my function:
double
distance(int x1, int y1, int x2, int y2)
{
double deltax = (double)x1 - x2;
double deltay = (double)y1 - y2;
return sqrt(deltax*deltax + deltay*deltay);
}
It works fine for most cases except that if deltax is really small
compared to deltay (or vice versa), the addition inside the sqrt
argument causes the smaller square value to be lost (because of adding
a large float number with a small float number)).
example: deltax = 1 deltay = 1999998
What this distance function returns is exactly what would be returned
if only one of the dimensions were 1999998.
This is crucial because I need the distance formula to work within a
certain tolerance so I can check to see if triangles are right or
oblique.
Does anyone know any tricks that I can use to preserve the "effect" of
the small deltax in the distance?
Thanks
I'm having trouble with floating point problems.
I'm trying to write a function that calculates the distance between two
cartesian points (integer coordinates). I have the function working,
but it fails on one test case.
Here is my function:
double
distance(int x1, int y1, int x2, int y2)
{
double deltax = (double)x1 - x2;
double deltay = (double)y1 - y2;
return sqrt(deltax*deltax + deltay*deltay);
}
It works fine for most cases except that if deltax is really small
compared to deltay (or vice versa), the addition inside the sqrt
argument causes the smaller square value to be lost (because of adding
a large float number with a small float number)).
example: deltax = 1 deltay = 1999998
What this distance function returns is exactly what would be returned
if only one of the dimensions were 1999998.
This is crucial because I need the distance formula to work within a
certain tolerance so I can check to see if triangles are right or
oblique.
Does anyone know any tricks that I can use to preserve the "effect" of
the small deltax in the distance?
Thanks