最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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))
发布评论

评论列表(0)

  1. 暂无评论