For example, if I use the following code to calculate the angle between two vectors x
and p
:
x = [1 1 -1];
p = [-1 -1 1];
angle = acos(dot(x,p) / (norm(x) * norm(p)));
it shows that angle = 3.141592653589793 - 0.000000021073424i
, which is a complex number.
But we all know that the dot product of x
and p
is -3, and the product of the norms of x
and p
is 3, so angle = acos(-3/3)
, so angle should be exactly pi, 3.14159. Why does MatLab give a complex number, and how do I make the result a real number instead?
Your problem starts with the normalisation:
norm(x) * norm(p)
Here you get a value which is slightly off the 3
which you would expect:
> (norm(x) * norm(p))-3
ans = -4.4409e-16
The error is propagated and you end up with a acos(x) where x is slighly above 1.
sqrt
is an operation which potentially causes irational results. When solving it with pen and paper, you would keep the square root and do the multiplication first. Rewrite it that way for better numerical probabillities:
angle = acos(dot(x,p) / sqrt(sum(x.^2)*sum(p.^2)))