Skip to content

Replace FP division with fixed-point shift in atan2 #110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/trig.c
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ static twin_angle_t twin_atan2_first_quadrant(twin_fixed_t y, twin_fixed_t x)
}
}

return (twin_angle_t) (double) angle / (32768.0) * TWIN_ANGLE_360;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this commit also aim to fix the incorrect casting of the variable angle from twin_angle_t to double?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this commit also aim to fix the incorrect casting of the variable angle from twin_angle_t to double?

Yes, intentionally.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then, why didn't you write this purpose on this commit log ?

/* Fixed-point conversion: angle * TWIN_ANGLE_360 / 32768 */
return (twin_angle_t) ((angle * TWIN_ANGLE_360) >> 15);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since TWIN_ANGLE_360=4096 = 2^12by simple simplification, the original expression can be represented as

$$\frac{\text{angle} * 4096}{32768} = \text{angle} * 2^{12} *2^{-15} = \text{angle} * 2^{-3}$$

which is equivalent to

+/* Fixed-point conversion: angle * TWIN_ANGLE_360 / 32768 */
+    return (twin_angle_t) (angle >> 3);

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the value range of angle is $[-9092,9092]$, using the original expression:

(angle * TWIN_ANGLE_360) >> 15

with TWIN_ANGLE_360 = 4096 can cause overflow. The maximum possible result of the multiplication is:

$$9092 * 4096 = 37,249,024$$

This value exceeds the limits of 16-bit, it may result in integer overflow and unpredictable behavior.

To avoid this issue, the multiplication and division can be replaced with a simple bit shift:

angle >> 3

}

twin_angle_t twin_atan2(twin_fixed_t y, twin_fixed_t x)
Expand Down