Skip to content

Instantly share code, notes, and snippets.

@horvatha
Created December 24, 2025 15:17
Show Gist options
  • Select an option

  • Save horvatha/a557aabfe636c39075c1ffe90c1eb311 to your computer and use it in GitHub Desktop.

Select an option

Save horvatha/a557aabfe636c39075c1ffe90c1eb311 to your computer and use it in GitHub Desktop.
import pytest
from cmath import exp, phase
from math import radians, pi
def closer_than_45_degree(deg1: int, deg2: int) -> bool:
d1 = deg1 % 360
d2 = deg2 % 360
if d1 > d2:
d1, d2 = d2, d1
# Now d2 >= d1 and both are between 0 and 359 degrees
if d2 - d1 < 45:
return True
d2 -= 360
if d1 - d2 < 45:
return True
return False
# For simplicity I just reuse the name
def closer_than_45_degree(deg1: float|int, deg2: float|int) -> bool:
c1 = exp(radians(deg1)*1j)
c2 = exp(radians(deg2)*1j)
rad_diff = phase(c1 / c2)
print(deg1, deg2, rad_diff)
# according to docs, the result is between -pi and pi
return abs(rad_diff) < pi/4
@pytest.mark.parametrize(
"deg1, deg2, result",
[
(0, 2, True),
(0, 72, False),
(-1, 3, True),
(-100, 3, False),
(5, 365, True),
(5, 3600025, True),
(5, 3600075, False),
(365, 3600075, False),
]
)
def test_values(deg1, deg2, result):
assert result == closer_than_45_degree(deg1, deg2)
assert result == closer_than_45_degree(deg2, deg1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment