Skip to content

Commit a0e12f2

Browse files
committed
Simplify fixed-pt conversion to avoid overflow
The previous implementation used ((angle * TWIN_ANGLE_360) >> 15) which caused integer overflow when angle values reached their maximum range of [-9092, 9092]. The multiplication 9092 * 4096 results in 37,240,832, exceeding the 16-bit signed integer limit. This commit simplifies the expression by factoring out the constants: - Original: angle * TWIN_ANGLE_360 / 32768 - Since TWIN_ANGLE_360 = 2^12 and 32768 = 2^15 - Simplified: angle * 2^12 / 2^15 = angle >> 3
1 parent 2e75289 commit a0e12f2

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

src/trig.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,11 @@ static twin_angle_t twin_atan2_first_quadrant(twin_fixed_t y, twin_fixed_t x)
148148
}
149149
}
150150

151-
return (twin_angle_t) (double) angle / (32768.0) * TWIN_ANGLE_360;
151+
/* Fixed-point conversion: angle / 32768 * TWIN_ANGLE_360
152+
* Simplified: angle * 2^12 / 2^15 = angle >> 3
153+
* Avoids overflow since 9092 * 4096 exceeds 16-bit range
154+
*/
155+
return (twin_angle_t) (angle >> 3);
152156
}
153157

154158
twin_angle_t twin_atan2(twin_fixed_t y, twin_fixed_t x)

0 commit comments

Comments
 (0)