Fomalhaut
Fomalhaut

Reputation: 9755

How to calculate an angle between 2D vector and OX with numpy?

Supposing, I have a 2D numpy array link this:

import numpy as np
v = np.array([1, 2])

I want to consider it as a vector at a 2D flat, that has axis OX and OY. I am curious, is there a build-in or quite elegant way to calculate the angle between the vector and the axis OX? The angle should be from -PI to PI.

I know, I could calculate with the help of numpy.arctan this way:

def calc_phi(v):
    if v[0] > 0:
        return np.arctan(v[1] / v[0])
    else:
        if v[1] > 0:
            if v[0] < 0:
                return np.pi + np.arctan(v[1] / v[0])
            else:
                return np.pi
        elif v[1] < 0:
            if v[0] < 0:
                return -np.pi + np.arctan(v[1] / v[0])
            else:
                return -np.pi
        else:
            return 0.0

But it doesn't seem to be elegant, because I have to separately consider the cases x = 0, and x < 0. So I think, numpy probably has a special function to calculate it.

Upvotes: 4

Views: 5757

Answers (1)

Joe Iddon
Joe Iddon

Reputation: 20424

You can use np.arctan2:

np.arctan2(*v)

However, as the angle is from the y-axis:

   |->
   |  \   #so this is the positive direction
   |   
-------
   |
   |

diagram probably won't help


It's necessary to swap the arguments to make it calculate the angle from X:

np.arctan2(v[1], v[0])

Upvotes: 3

Related Questions