math.sqrt returns 0

1.7k views Asked by At

I have a c# function that contains formula to calculate euclidean distance of some points. I got the point's position defined by R(rx,ry) and L(lx,ly).

at first, I tried to write the code like this:

double dRightLeft = Math.Sqrt((Math.Pow(rx - lx, 2) + Math.Pow(ry - ly, 2)));

it returns 0.0.

then I tried to split the variable to check where did I do wrong, like this:

 double rl = (Math.Pow(rx - lx, 2) + Math.Pow(ry - ly, 2));
 double dRightLeft = Math.Sqrt(rl);

the rl variable returns a valid value of its operation. but then when I tried to get the square root out of it, the dRighLeft variable still returns 0.0. I tried both assigned and unassigned dRightLeft like this:

//assigned
dRightLeft = 0;
//unassigned
dRightLeft;

they both still returns 0.0 value.

here's my short but complete program where I get the rx, ry, lx, and ly value:

public Bitmap getDetectedImage()
{
int rx, rx, lx, ly, ...;
double dRightLeft = 0;
...
//righteyeloop
for (int x = fo.rightEye.X; x < (fo.rightEye.X + fo.rightEye.Width); x++)
{
    for (int y = fo.rightEye.Y; y < (fo.rightEye.Y + fo.rightEye.Height); y++)
    {    //segmentation...//   
         rPixel++;
         result.byteImage[x, y].R = 0;
         result.byteImage[x, y].G = 255;
         result.byteImage[x, y].B = 0;
//to get the the first pixel detected//
         if (rPixel == 1)
         {
             result.byteImage[x, y].R = 255;
             result.byteImage[x, y].G = 0;
             result.byteImage[x, y].B = 0;

rx = x + (fo.rightEye.Width / setting.featureWidth * setting.eyeHeight / setting.eyeWidth);
ry = y + (fo.rightEye.Height / setting.featureWidth * setting.eyeHeight / setting.eyeWidth);
         }
    }
}
//lefteyeloop basically the same type as righteyeloop//
.....
//this to count the distance of righteye and lefteye
    double rl = ((rx - lx) * (rx - lx) + (ry - ly) * (ry - ly));
    double dRightLeft = Math.Pow(rl, 0.5);
}
1

There are 1 answers

3
ajiang On

I suspect the problem is that Math.Pow deals with doubles, which have low precision (see this SO question for more discussion). The immediate instinct is to just replace Math.Pow by writing out the multiplication:

double rl = ((rx - lx) * (rx - lx) + (ry - ly) * (ry - ly));
double dRightLeft = Math.Sqrt(rl);

From the Math.Pow reference, it seems that, with an exponent of two, the only way to return 0 is if your base (i.e. rx - lx or ry - ly) is also 0.