Search code examples
pythonnumpynavigationlinear-interpolationheading

How can I deal with passing 360 degrees when I linearly interpolate between two headings?


A part of my python program linearly interpolates between two compass headings. It works fine as long as I don't have to deal with passing through North. Is there a good way to deal with this rather simplistic interpolation? For example, the midpoint between 340 and 010 should be 355 and not 175. Thanks in advance.

I'm using numpy.interp(x, xp, fp) and it usually works. Sometimes however, I get a 180 degree error such as the interpolation between heading 340 and 010.


Solution

  • This is a common issue for calculation with angles, and the most common method to fix is to add a dimension. In this case, we replace each angle with a vector if its sine and cosine.

    theta = np.array([340, 10])
    theta = theta * np.pi / 180  #radians
    theta_2d = np.array([np.sin(theta), np.cos(theta)])
    avg = np.arctan2(*theta_2d.mean(1)) 
    print((avg * 180 / np.pi) % 360)  # back to degrees, on the interval [0, 360)
    
    355.0
    

    There is a special case in this method that the average of angles exactly 180 degrees apart will be undefined: arctan2(0, 0) doesn't have an answer - but then, it was kinda undefined before, as there's two valid answers. If necessary that edge case can be handled, but more information on how it needs to be handled would need to come from you.

    This can be expanded to np.interp (average is just interp at .5) but without test code it's a bit hard to see exactly how the implementation might come together in your case.