Sign in to follow this  
fguihen

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 this post


Link to post
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 this post


Link to post
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));

instead than

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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...)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this