'Finding angle between two unit vectors in three dimensions

I am trying to do some basic 3D simulation but it has been 20 years since I learned this stuff in high school...

If I have two vectors in three dimensions, how do I find the angle between them. For example I have one vector of (3,2,1) and another of (4,-5,6) how would I find the angle (in degrees or radians) between them. If I recall there was some formula to do this.

Thanks.



Solution 1:[1]

This does the trick:

atan2(sqrt(dot(cross(a, b), cross(a, b))), dot(a, b))

as a python lambda function:

import math, numpy

angle = lambda a, b: math.atan2(
    math.sqrt(
        numpy.dot(*([numpy.cross(a, b)]*2))
    ), 
    numpy.dot(a, b)
)

results are in radians:

In : angle([1.,1.,1.], [-1.,1.,1.])
Out: 1.2309594173407747

In : angle([0.,1.,0.], [0.,0.,1.])
Out: 1.5707963267948966

works in 2 dimensions as well:

In : angle([0.,1.], [1.,0.])
Out: 1.5707963267948966

In : angle([0.,1.], [1.,1.])
Out: 0.7853981633974483

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1