Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a complex number using acos?

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?

like image 880
FalloutRanger Avatar asked May 07 '26 17:05

FalloutRanger


1 Answers

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)))
like image 56
Daniel Avatar answered May 11 '26 04:05

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!