Skip to content
Center periodic offsets with Python math.remainder

Center periodic offsets with Python math.remainder

November 22, 2026

Comparing an orientation with a reference often needs a signed offset near zero. An angle of 350 degrees can be represented as a small negative offset, while a phase stored in the usual zero-to-360 interval remains positive.

Run the example

Tested on Linux with Python 3.12.14. No third-party packages are required. In one Bash session, create a disposable directory:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Save this as demo_python_remainder_centered_periodic_offset.py. Use that filename to avoid shadowing a standard-library module.

from math import remainder

for angle in (350.0, -350.0, 180.0, 540.0):
    print(f"{angle:.0f}: centered={remainder(angle, 360.0):.0f}, modulo={angle % 360.0:.0f}")

def normalized_heading(angle):
    return angle % 360.0

print("stored heading:", normalized_heading(-10.0))

Run it:

python3 demo_python_remainder_centered_periodic_offset.py

Output:

350: centered=-10, modulo=350
-350: centered=10, modulo=10
180: centered=180, modulo=180
540: centered=-180, modulo=180
stored heading: 350.0

remainder chooses the nearest integer quotient; ties use the even quotient. Consequently, the half-turn can appear as either positive or negative 180 depending on the input. Modulo with a positive period instead produces the familiar nonnegative representation for these inputs.

Input policy and limits

Choose and document the half-period convention before using this result in a controller or comparison rule. The two signed half-turn values describe the same orientation but may drive different decisions. Use finite angles and a finite positive period; zero is not a valid divisor. This example illustrates representation only and is not control-system code.

Clean up

In the same Bash session, remove the source file and the empty working directory:

rm -- demo_python_remainder_centered_periodic_offset.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect its contents before deleting anything else.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on