2

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.

user631589
  • 43
  • 1
  • 2
  • 6
  • 1
    Actually, you should probably consider carefully whether you really need the angle at all. The math is often simpler (and the computation faster) if you use vector math to avoid converting to and from angles whenever possible. – comingstorm Feb 24 '11 at 09:27
  • Does this answer your question? [Using atan2 to find angle between two vectors](https://stackoverflow.com/questions/21483999/using-atan2-to-find-angle-between-two-vectors) – John Alexiou Jul 15 '22 at 01:40
  • Four **unit** vectors `angle = acos(dot(a,b))`. Vectors in your example are not unit ones, so divide dot result by product of magnitudes – MBo Jul 15 '23 at 02:59

1 Answers1

0

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
ox.
  • 3,579
  • 1
  • 21
  • 21