开发者

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;
        ind开发者_如何学Pythonex = z;
    }
}

Does anyone have an idea what the problem could be?


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;


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.


^ is the xor operator; it does not perform exponentiation.

In the general case, if you want to raise something to a power, you should use the std::pow function. However, in this specific case, since it is the square, you're probably better off just using multiplication (e.g., x * x instead of std::pow(x, 2)).


Note that in C++ the caret (^) is not an exponentiation operator. Rather, it's a bitwise exclusive or.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜