1
Programming / Angle wrapping in code, "easy" problem, need to double check
« Last post by Infraviolet on Today at 09:14:35 pm »Is this always guaranteed to work for integers:
int16_t Clamp360(int16_t value){
value= value % 360;
if(value >= 0){
return value;
}else{
return 360 - (0 - value);
}
}
In languages like C and C++ where % is modulo, not truly a remainder and therefore returns negative results when negativeNum % positiveNum is done.
I'd rather avoid resorting to sin, cos and atan2 because this needs to run fast on a microcontroller in the end, so I'm trying to avoid trig functions or proper dot and cross products. And I'd also like not to have a while loop which may go on for a very long time if it subtracts 360 each time.
I've tested for all integers -1080 to +1080 and it plots out the right graph for input vs output, but I've had nasty experiences with angle wrapping code before. I want to make sure this is right before I continue with any further code built around it.
Is this a guaranteed solution for signed integer variables? Will it also be one if floating point variables are used instead?
Thanks
int16_t Clamp360(int16_t value){
value= value % 360;
if(value >= 0){
return value;
}else{
return 360 - (0 - value);
}
}
In languages like C and C++ where % is modulo, not truly a remainder and therefore returns negative results when negativeNum % positiveNum is done.
I'd rather avoid resorting to sin, cos and atan2 because this needs to run fast on a microcontroller in the end, so I'm trying to avoid trig functions or proper dot and cross products. And I'd also like not to have a while loop which may go on for a very long time if it subtracts 360 each time.
I've tested for all integers -1080 to +1080 and it plots out the right graph for input vs output, but I've had nasty experiences with angle wrapping code before. I want to make sure this is right before I continue with any further code built around it.
Is this a guaranteed solution for signed integer variables? Will it also be one if floating point variables are used instead?
Thanks