Teensy 4.1 Weird Error adding long values

zm350

New member
Hi

I am actually trying to average some values using teensy 4.1.
The result didnt make sense so I started printing stuff. I realised at some point the sign of the sum was flipped ...
Here the result of the printing, l_val2 is the sum and val2 the current value both variables are type long.


val2=-8327505Before l_val2=-2116246172After l_val2=-2124573677 mesCount=255.00
val2=-8315780Before l_val2=-2124573677After l_val2=-2132889457 mesCount=256.00
val2=-8317752Before l_val2=-2132889457After l_val2=-2141207209 mesCount=257.00
val2=-8337528Before l_val2=-2141207209After l_val2=2145422559 mesCount=258.00
val2=-8329891Before l_val2=2145422559After l_val2=2137092668 mesCount=259.00
val2=-8335188Before l_val2=2137092668After l_val2=2128757480 mesCount=260.00

Between mesCount=258.00 and mesCount=259.00 l_val2 has flipped from negative to positive when we are adding a negative value to a negative sum .........
Any ideas ? is there some specific rules as to additions using microcontroller ?
 
Just to add the code:

Code:
Serial.print("val2=");
  Serial.print(val2);
  
  l_val1 = l_val1 + val1;
  
  Serial.print("Before l_val2=");
  Serial.print(l_val2);
  l_val2 = l_val2 + val2;
  Serial.print("After l_val2=");
  Serial.print(l_val2);
  l_val3 = l_val3 + val3;
 
  mesCount ++;

  Serial.print(" mesCount=");
  Serial.println(mesCount);
 
long values are 32 bits. Signed long values have range -2147483648 to +2147483647. If you keep adding negative numbers, your sum will eventually roll over to the positive range, and if you add positive numbers, you can roll over to the negative range. If you need a larger range, you can use 64-bit type long long. Even with 64 bits you can have roll over, so don't expect to be able to add large negative (or positive) integers forever. If you use floating point (type float or type double), you get a larger range, but limited precision.
 
Ok I see i thought it was 64 bits on teensy. I switched from int32_t to long actually thinking it was ok :) :) .I'll use long long thanks!
 
Back
Top