Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve the angle between two vectors 3D?

I am new in python. I have two vectors in 3d space, and I want to know the angle between two

I tried:

vec1=[x1,y1,z1]

vec2=[x2,y2,z2]

angle=np.arccos(np.dot(vec1,vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2)))

but when change the order, vec2,vec1 obtain the same angle and no higher. I want to give me a greater angle when the order of the vectors changes.

like image 247
Alberto Alarcon Paredes Avatar asked Dec 04 '22 23:12

Alberto Alarcon Paredes


1 Answers

Use a function to help you choose which angle do you want. In the beggining of your code, write:

def angle(v1, v2, acute):
# v1 is your firsr vector
# v2 is your second vector
    angle = np.arccos(np.dot(v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
    if (acute == True):
        return angle
    else:
        return 2 * np.pi - angle

Then, when you want to calculate an angle (in radians) in your program just write

angle(vec1, vec2, 'True')

for acute angles, and

angle(vec2, vec1, 'False')

for obtuse angles.

For example:

vec1 = [1, -1, 0]
vec2 = [1, 1, 0]

#I am explicitly converting from radian to degree
print(180* angle(vec1, vec2, True)/np.pi) #90 degrees
print(180* angle(vec2, vec1, False)/np.pi) #270 degrees
like image 143
Arthur Avatar answered Dec 31 '22 06:12

Arthur