# method to find angle between vectors

## Recommended Posts

fguihen    100
this method is supposed to find the angle between vecotrs. its not fully working and im not sure why. any ideas?
public static float AngleBetweenVectors(Vector point1, Vector point2)//finds the angle between two vectors
{
float theta = Dot(point1,point2) / (Length(point1) * Length(point2));
theta = (float)Math.Cos((double)theta);
return theta;
}


##### Share on other sites
d00fus    328
Dot(point1, point2)/(Length(point1)*Length(point2)) gives you cos(theta), not theta. So what you want on the 2nd line of the function is

theta = (float)Math.Acos((double)theta);

##### Share on other sites
cignox1    735
Sorry, but I don't understand a thing: why do you do:

float theta = Dot(point1,point2) / (Length(point1) * Length(point2));

float theta = Dot(point1,point2);

Perhaps I'm missing something, but I think you don't need to scale the dot result...but I could be wrong...

##### Share on other sites
Trap    684
a dot b = length(a)*length(b)*cos(theta)

Thats how dot is defined without using coordinates.

Edit: cos was missing...

##### Share on other sites
Skizz    794
It's because the dot product is defined as:

dot_prod = |A|.|B|.cos theta (1)

where theta is the angle between the vectors. It can also be defined as:

dot_prod = ai.bi + aj.bj + ... (2)

So, given we know the value of the dot product from equation (2), substituting it into (1) will produce the result d00fus posted.

Skizz

##### Share on other sites
JohnBolton    1372
You must clamp the input to acos() to the range [-1, 1] because it could end up outside of that range due to precision error, and acos() will return NaN.

##### Share on other sites
cignox1    735
Thank you, I have to remember this: I'm just writing a geometric library for my ray-tracer, and I completely forgot this (running checking the code...)