C ++ euclidean distance

This code compiles and runs, but does not output the correct distances.

for (int z = 0; z < spaces_x; z++)
{
    double dist=( ( (spaces[z][0]-x)^2) + ( (spaces[z][1]-y)^2) );
    dist = abs(dist);   
    dist = sqrt(dist);
    cout << "for x " << spaces[z][0] <<
            " for y " << spaces[z][1] <<
            " dist is  "<< dist << endl;

    if (dist < min_dist)
    {
        min_dist = dist;
        index = z;
    }
}

      

Anyone can figure out what the problem might be?

+2


a source to share


4 answers


The syntax ^ 2

doesn't mean promoted to a power of 2 - it means XOR. Use x * x

.



double dx = spaces[z][0] - x;
double dy = spaces[z][1] - y;
double dist2 = dx * dx + dy * dy;

      

+21


a source


It might be better to use hypot()

instead of manual squaring and adding and taking the square root. hypot()

takes care of a number of cases where the naive approach loses precision. It's part of C99 and C ++ 0x, and for compilers that don't have it, it's always boost.math .



+7


a source


^

- operator xor

; it does not perform exponentiation.

In general, if you want to raise something, you should use the function std::pow

. However, in this particular case, since it is a square, you are probably better off just using multiplication (e.g. x * x

instead of std::pow(x, 2)

).

+6


a source


Note that in C ++, caret ( ^

) is not an exponentiation operator. Rather, it is a bitwise exception or.

+2


a source







All Articles