-
Notifications
You must be signed in to change notification settings - Fork 657
Description
Issue Description:
I have identified a potential logic bug in the optimized trigonometric functions in foc_utils.cpp. The code currently performs a direct cast from a float to an unsigned int, which results in undefined behavior when the input angle a is negative.
Affected Code:
In src/common/foc_utils.cpp:
_sin(float a)_cos(float a)(indirectly)
// Current implementation
unsigned int i = (unsigned int)(a * (64*4*256.0f/_2PI));Technical Explanation:
According to the C++ standard (ISO/IEC 14882), casting a negative floating-point value to an unsigned integer type is undefined.
While the library typically calls _normalizeAngle before using these functions in the main FOC loop, if a user or a different part of the library calls _sin() with a negative angle, the unsigned int cast can result in a value that breaks the quadrant logic.
For example, on many MCUs, a negative float cast to unsigned int will saturate to 0 or wrap to a massive integer, leading to an incorrect index i and an incorrect sine result.
Suggested Fix:
Changing the type of i from unsigned int to a signed int ensures the cast is well-defined. The subsequent bitwise operations (& 0xff and >> 8) will still function correctly to resolve the table index and fractional part.
// Suggested change
int i = (int)(a * (64*4*256.0f/_2PI));