Commit 439545f
committed
Fix conversion precision to avoid overflow
The previous implementation used ((angle * TWIN_ANGLE_360) >> 15) which
caused two critical issues:
1. Integer Overflow:
The multiplication 9092 * 4096 results in 37,240,832, exceeding the
16-bit signed integer limit (32,767). It occurs when CORDIC iteration
reaches maximum angle accumulation.
2. Precision Error for Negative Values:
Right shift (>>) rounds towards negative infinity (floor division),
while the original floating-point cast truncates towards zero.
This causes precision errors for ~87.5% of negative angle values
(all non-multiples of 8).
Examples:
- Original: (int)(-7 / 32768.0 * 4096) = 0
- Right shift: -7 >> 3 = -1 (WRONG)
- Integer division: -7 / 8 = 0 (CORRECT)
This commit simplifies the expression by factoring out constants:
- Original: angle * TWIN_ANGLE_360 / 32768
- Since TWIN_ANGLE_360 = 2^12 and 32768 = 2^15
- Simplified: angle * 2^12 / 2^15 = angle / 8
This uses integer division (/) instead of right shift (>>) to match the
original truncate-towards-zero behavior guaranteed by C99, preserving
exact precision for all angle values in CORDIC's [-9092, 9092] range.1 parent 2e75289 commit 439545f
1 file changed
+9
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
148 | 148 | | |
149 | 149 | | |
150 | 150 | | |
151 | | - | |
| 151 | + | |
| 152 | + | |
| 153 | + | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
| 159 | + | |
152 | 160 | | |
153 | 161 | | |
154 | 162 | | |
| |||
0 commit comments