The easiest way is to simply use min:
def angular_distance(theta_1, theta_2, mod=2*math.pi): difference = abs(theta_1 % mod - theta_2 % mod) return min(difference, mod - difference) def nearest_angle(L, theta): return min(L, key=lambda theta_1: angular_distance(theta, theta_2)) In [11]: min(L, key=lambda theta: angular_distance(theta, 1)) Out[11]: 1.1
Using list sorting, you can use the bisect module:
from bisect import bisect_left def nearest_angle_b(theta, sorted_list, mod=2*math.pi): i1 = bisect_left(sorted_list, theta % mod) if i1 == 0: i1, i2 = len(sorted_list) - 1, 0 elif i1 == len(sorted_list): i1, i2 = i1 - 1, 0 else: i2 = (i1 + 1) % len(sorted_list) return min((angular_distance(theta, L[i], mod), i, L[i]) for i in [i1, i2])
Returns the distance, index, and angle in the list to which it is closest.
source share