Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ euclidean distance

Tags:

c++

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;
    }
}

Does anyone have an idea what the problem could be?

like image 246
juan Avatar asked Nov 27 '22 01:11

juan


2 Answers

The syntax ^ 2 does not mean raise to the 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;
like image 152
Mark Byers Avatar answered Dec 11 '22 07:12

Mark Byers


It may be a better idea to use hypot() instead of manually squaring and adding and taking a the square root. hypot() takes care of a number of cases where naive approach would lose precision. It is a part of C99 and C++0x, and for the compilers that don't have it, there's always boost.math.

like image 44
Cubbi Avatar answered Dec 11 '22 08:12

Cubbi