# method to find angle between vectors

This topic is 4843 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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
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
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
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
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
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
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...)

• 40
• 15
• 10
• 23
• 19