In
R
, given two vectors
v,
w at the
origin, in talking about the angle
between them you might
as well allow only values
, because the
same angle can look clockwise or counterclockwise when seen from
different directions. To find
, it's enough to use the
dot product, which works in
R
for any
. As in Section
3 above:
(1)
.
In
R
, though, it makes sense to ask for
with a sign.
means a counterclockwise angle and
means a clockwise angle. Possible values would be
. This time dot products alone are not
enough, because with cosines you can't tell the difference
between
and
; for example,
.
You might at first consider using
instead. In fact, there is a corresponding formula, as noted
in section 5 above:
(2)
v
w
, where
v
w
.
However, with sines you can't tell the difference between
and
; for example,
.
What about the tangent function? From (1) and (2) we would get
(3)
,
where the denominators have been canceled. But the tangent
has a similar problem: it can't distinguish between
and
.
One way to get an exact
would be to use two trig
functions. Since you're solving for
you would use two of
the arc functions, which in C and C++ are acos( ),
asin( ), and atan( ). The first would give you an angle
in a specific range such as
for acos( ),
and then you would use the second to change the angle if warranted
(say, negating the angle if asin( ) is negative).
Fortunately, though, there is a single function in C and C++ that is
designed expressly for this kind of application: the
atan2(y,x) function. This function finds
while paying attention to whether
and
are positive,
negative, or zero; it returns a value between
and
, as
desired. It works even if the denominator x is zero!
Thus in C or C++ (using subscripts 0,1 for 1,2), you can find
by
(4) theta = atan2(v[0]*w[1]-v[1]*w[0], v[0]*w[0]+v[1]*w[1]);
There will be an error if both arguments are zero.
Note. In some versions of C and C++ this function may be built in;
in others you may need to use #include<math.h> and to compile with a
flag -lm. This kind of function is also available in other languages,
but check which argument is for x and which for y.