Silly Obvious Question On Angles

Started by
2 comments, last by fathom88 17 years, 8 months ago
Hi, I have a silly question on angles. I know it's just a trig formula but I can't seem to remember it. I have three points (x1,y1), (x2,y2), and (x3,y3). One point is always at the origin. Hence, I get two connected lines. For example, my points could be 0,3, 0,0, 3,0 and my resulting angle would be 90 degrees. If my points were 0,3, 0,0 0,-3, my angle would be 180 degrees. You get the idea. I seem to remember having to find the dot product 1st. Thanks. Sorry for asking such a lame question.
Advertisement
In two dimensions, you could resort to two calls to atan2.
First of all, substract the coordinates of the "origin" from the other two points, so now you actually have two vectors, (x1,y1) and (x2,y2). Now compute the dot product of the two vectors (x1*x2,y1*y2) and divide it by the length of each vector. The result is the cosine of the angle (this is a common definition of "angle", actually).

The same approach works for vectors in higher dimension.

#include <iostream>#include <cmath>const double Pi=std::atan(1.0)*4;struct Vector2D {  double x,y;  Vector2D(double x, double y):x(x),y(y){  }  double dot(Vector2D const &v) const{    return x*v.x+y*v.y;  }  double length() const{    return std::sqrt(this->dot(*this));  }};struct Point2D {  double x,y;  Point2D(double x, double y):x(x),y(y){  }  Vector2D operator-(Point2D const &p) const{    return Vector2D(x-p.x,y-p.y);  }};int main(){  Point2D x1(0,3),x2(0,0),x3(3,0);  Vector2D v1=x1-x2;  Vector2D v2=x3-x2;  double cosine=v1.dot(v2)/(v1.length()*v2.length());  double angle=std::acos(cosine);  std::cout << angle*180/Pi << std::endl;}
Thanks for the help.

This topic is closed to new replies.

Advertisement