tags:

views:

219

answers:

4

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?

+6  A: 

^ 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)).

James McNellis
std::pow will use a shortcut if you call it with an integer for the power.
Martin Beckett
I've seen at least a couple implementations of pow that are rather poor and don't do any such optimization. In general don't count on it.
Mark B
A: 

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

Kaleb Pederson
It's called a "caret," not a carrot :)
rlbond
Surely carrot is the name for !
High Performance Mark
It's bitwise *xor*, not *or*.
FredOverflow
Wow, two careless mistakes in a single post. Sorry, fixed.
Kaleb Pederson
+18  A: 

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;
Mark Byers
+1. Also, dist=abs(dist) is unnecessary. A sum of two powers will always be positive.
Fabio Ceconello
+5  A: 

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.

Cubbi
Or just leave it as distance squared for this calculation. The item with the smallest distance will also have the smallest distance squared.
Mark Byers