Skip to content

Commit 8a03ba4

Browse files
authored
Merge pull request #110 from sysprog21/fixedpoint-atan2
Fix fixed-point conversion precision to avoid overflow
2 parents c0bd1e8 + 439545f commit 8a03ba4

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

src/trig.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,15 @@ 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 / 8
153+
* Use integer division (not right shift) to match original
154+
* truncate-towards-zero behavior for negative values. Right shift would
155+
* round towards negative infinity, causing precision errors for
156+
* non-multiples of 8. Avoids overflow since no intermediate multiplication
157+
* required.
158+
*/
159+
return (twin_angle_t) (angle / 8);
152160
}
153161

154162
twin_angle_t twin_atan2(twin_fixed_t y, twin_fixed_t x)

0 commit comments

Comments
 (0)