## 10/25/2012

### Inner product(the angle between the two lines) - function source code

If there are 3 point(c, p1, p2), as shown in the above figure.
This function got the angle between the two lines using inner product.
Even if the name changed from (p1, p2) to (p2, p1),  the function get the narrow angle between the two lines.

I hope this code useful to you.
thank you.

float innerAngle(float px1, float py1, float px2, float py2, float cx1, float cy1)
{

float dist1 = sqrt(  (px1-cx1)*(px1-cx1) + (py1-cy1)*(py1-cy1) );
float dist2 = sqrt(  (px2-cx1)*(px2-cx1) + (py2-cy1)*(py2-cy1) );

float Ax, Ay;
float Bx, By;
float Cx, Cy;

//find closest point to C
//printf("dist = %lf %lf\n", dist1, dist2);

Cx = cx1;
Cy = cy1;
if(dist1 < dist2)
{
Bx = px1;
By = py1;
Ax = px2;
Ay = py2;

}else{
Bx = px2;
By = py2;
Ax = px1;
Ay = py1;
}

float Q1 = Cx - Ax;
float Q2 = Cy - Ay;
float P1 = Bx - Ax;
float P2 = By - Ay;

float A = acos( (P1*Q1 + P2*Q2) / ( sqrt(P1*P1+P2*P2) * sqrt(Q1*Q1+Q2*Q2) ) );

A = A*180/PI;

return A;
}



1. Anonymous27/5/13 07:50

hi jeong hyun,

thanks a lot for your code. are you sure it is correct though? i could not get the right angles for my points until i changed the definition of P1 and P2. maybe it was my mistake though.

greetings

2. em.. could you give me your example point?
then I will check my code again.
Thank you for visiting my blog.

3. The code is not correct I think...

Points (50,80), (30,60) and (50,60) always give 45 instead of 90. To fix it you have to replace the part with the distances (the if) by:
Bx = px1; By = py1;
Ax = px2; Ay = py2;

Thanks for the rest of the code. :)