Sorry for the pretty dumb question. I'm slowly learning maths from scratch.
I would like to calculate the angle of triangle through javascript.
I calculate the lengths of the sides,
Ab = Math.abs(b.x - c.x);
Ac = Math.abs(b.y - c.y);
A = Math.sqrt((Ab*Ab) + (Ac*Ac));
Bb = Math.abs(a.x - c.x);
Bc = Math.abs(a.y - c.y);
B = Math.sqrt((Bb*Bb) + (Bc*Bc));
Cb = Math.abs(a.x - b.x);
Cc = Math.abs(a.y - b.y);
C = Math.sqrt((Cb*Cb) + (Cc*Cc));
And then I get to this point:
angleB = Math.cos(((C*C) + (A*A) - (B*B))/(2*C*A));
However, I get a pletely wrong number. Why is this so?
Sorry for the pretty dumb question. I'm slowly learning maths from scratch.
I would like to calculate the angle of triangle through javascript.
I calculate the lengths of the sides,
Ab = Math.abs(b.x - c.x);
Ac = Math.abs(b.y - c.y);
A = Math.sqrt((Ab*Ab) + (Ac*Ac));
Bb = Math.abs(a.x - c.x);
Bc = Math.abs(a.y - c.y);
B = Math.sqrt((Bb*Bb) + (Bc*Bc));
Cb = Math.abs(a.x - b.x);
Cc = Math.abs(a.y - b.y);
C = Math.sqrt((Cb*Cb) + (Cc*Cc));
And then I get to this point:
angleB = Math.cos(((C*C) + (A*A) - (B*B))/(2*C*A));
However, I get a pletely wrong number. Why is this so?
Share Improve this question edited Jun 21, 2013 at 14:37 styke asked Jun 21, 2013 at 14:31 stykestyke 2,1742 gold badges27 silver badges54 bronze badges 4- Maybe you don't realize that most languages deal with radians, but you're expecting degrees. It'll be easy to tell if you post the number you get and the one you expect. – duffymo Commented Jun 21, 2013 at 14:33
- Triangles have three angles. Which are you trying to calculate? – Ignacio Vazquez-Abrams Commented Jun 21, 2013 at 14:34
- Where's the rest of your code? Which 'angle' are you looking for? – shennan Commented Jun 21, 2013 at 14:35
- 1 He's looking for angle B, which is the angle opposite side B. – Kevin Commented Jun 21, 2013 at 14:36
1 Answer
Reset to default 5Your code uses Math.cos
when it should use Math.acos
.
Starting with the law of cosines, we derive the correct formula:
b*b = a*a + c*c - 2*a*c*cos(angleB)
b*b - a*a - c*c = - 2*a*c*cos(angleB)
2*a*c*cos(angleB) = a*a + c*c - b*b
cos(angleB) = (a*a + c*c - b*b) / (2*a*c)
angleB = acos((a*a + c*c - b*b) / (2*a*c))