How can one understand the ATAN2() function for calculating the angle between 2 vectors?

1k Views Asked by At

It took me long time to find a good formula to calculate the confined angle between two $2D$-vectors for example $(u,v)$. I have found the following formula:

$θ=2\operatorname{atan2}\left(\bigl\| \|v\|u−\|u\|v \bigr\|, \bigl\| \|v\|u+\|u\|v \bigr\|\right)$

where $\|u\|$ and $\|v\|$ are the length of the vector $u$ and $v$ respectively. AS we know:

$\cos(x)= \text{adjacent/hypotenuse}$

$\sin(x) = \text{opposite/hypotenuse}$

$\tan(x) = \text{adjacent/adjacent}$

So how can one interpret $\operatorname{atan2}\left(\bigl\| \|v\|u−\|u\|v \bigr\|, \bigl\| \|v\|u+\|u\|v \bigr\|\right)$ function in calculating the confined angle?

2

There are 2 best solutions below

1
On BEST ANSWER

That looks horribly complicated, and all those norms can't be cheap to compute. What I'd do given vectors $u=(x_1,y_1)$ and $v=(x_2,y_2)$ is first consider the matrix $$ \begin{pmatrix} x_1 & y_1 \\ -y_1 & x_1 \end{pmatrix} $$ which is a combination of a scaling by $|u|$ (which for the purpose of angles we can ignore) and a rotation matrix that rotates $u$ down to the positive $x$-axis. Therefore, $$ \begin{pmatrix} x_1 & y_1 \\ -y_1 & x_1 \end{pmatrix} \begin{pmatrix} x_2 \\ y_2 \end{pmatrix} = \begin{pmatrix} x_1x_2 + y_1y_2 \\ x_1y_2 - x_2y_1 \end{pmatrix} $$ has the same angle with the $x$-axis as $v$ has to $u$, and you can then compute this angle as $$ \operatorname{atan2}(x_1x_2 + y_1y_2, x_1y_2 - x_2y_1 ) $$ (or the other way around, depending on your programming languages's conventions for the order of the arguments to atan2).

3
On

It’s easier to understand if you rearrange things a bit. Assuming that neither $u$ nor $v$ is zero, consider the unit vectors $u' = {u\over\|u\|}$ and $v' = {v\over\|v\|}$. $u'+v'$ and $u'-v'$ are the diagonals of the rhombus formed by these unit vectors. These diagonals bisect the vertex angles and are perpendicular to and bisect each other, so it should be fairly clear that if $\theta$ is the angle between $u'$ and $v'$, then $\tan\frac\theta2 = {\|u'-v'\|/2 \over \|u'+v'\|/2} = {\|u'-v'\| \over \|u'+v'\|}$. Multiply both the numerator and denominator by $\|u\|\|v\|$ to obtain $$\tan\frac\theta2 = {\bigl\|\|v\|u-\|u\|v\bigr\| \over \bigl\|\|v\|u+\|u\|v\bigr\|},$$ and solve for $\theta$ to get the formula in your question. This equation also gives you expressions for the angle bisectors of two arbitrary nonzero vectors $u$ and $v$: they are $\|v\|u\pm\|u\|v$.

That said, this requires computing four vector norms so doesn’t look to me like a particularly efficient way to compute this angle. As a much more efficient alternative, we know that $$u\cdot v=u_xv_x+u_yv_y = \|u\|\|v\|\cos\theta \\ \det\begin{bmatrix}u&v\end{bmatrix} = u_xv_y-u_yv_x = \|u\|\|v\|\sin\theta$$ therefore $$\tan\theta = {u_xv_y-u_yv_x \over u_xv_x+u_yv_y}.$$