math - Calculating an angle of a triangle with Javascript? - Stack Overflow

Sorry for the pretty dumb question. I'm slowly learning maths from scratch.I would like to calcul

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
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745133235a4613075.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信