Issue with calculating magnitude using integers

Hello,

I'm currently trying to calculate the magnitude of a vector, but am having some trouble with receiving any values larger than 180 when reading the returned values through the serial monitor.

When reading this data, the value increase until around 180 before turning to 0 and repeating this cycle.

If possible I'd really appreciate any help with trying to understand why this is the case. I've spent some time reading through the arduino forums and have found that replacing the integers with long variables seems to fix this issue, however I've not been able to understand why.

I have been reading about the limits when using integers, however as the numbers I am working with are fairly small I've been unsure about why exactly this limit seems to be being reached.

The code that I've been using for this calculation is as follows :

int x = 0;
int y = 0;
int x2 = 0;
int y2 = 0;

void setup() {

Serial.begin(115200); // set data rate

}

void loop() {

delay(20);

// add onto x2 value
x2 += 1;

//
int newX = x2 - x;
int newY = y2 - y;

int distance = (int)sqrt(newXnewX + newYnewY);

Serial.println(distance);

}

If anyone might be able to help me understand this your help would really be appreciated.

've been unsure about why exactly this limit seems to be being reached.

newX*newX

is not small!

Mark

Hint: what is the largest value that a 16 bit "int" can hold?

Thanks for both your responses.

I have indeed overlooked the fact that these values do become very large as the code continues to run, which in turn means that they are reaching the limit that can be here with an integer.

I think perhaps I need to rethink how I approach finding the distance so that these values that I do receive back aren't so large.

Or use long ints.