Square of the variable is negative

Hi,
I’m so new to the arduino and this forum.
My question is - why I’m getting negative value (a) of the square of my ax axis. And actually, itsn’t square of ax value.

My code is:

#include "MPU6050.h"
MPU6050 accelgyro;

int16_t ax, ay, az;
int16_t gx, gy, gz;

void setup() {
    Serial.begin(9600);
    accelgyro.initialize();

}

void loop() {
    accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
 if (ax < 0)
          {ax = -ax;
}
        Serial.print("ax = "); Serial.println(ax);
        int a = sq(ax);
        Serial.print("a = "); Serial.println(a);
delay(500);
}

thank you

Multiplying int16_t by int16_t gives an intermediate int16_t result. If you multiply 1000*1000, the result won't fit in int16_t and (IIRC) you get the low-order 16 bits of the result. Using "ax = -ax" will make the result positive but it still won't have the correct magnitude.

Pete

thanks!

You need to use variables that are a suitable size to hold the intermediate and final values for a calculation.

It can help to plan the order of calculation so as to keep the size of intermediate values reasonable.

...R