Advertisement
yamaji14

Angle between Lines

Jan 16th, 2015
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <math.h>
  2. #include <iostream>
  3.  
  4. template <typename T> class Vector2D
  5. {
  6. private:
  7.     T x;
  8.     T y;
  9.  
  10. public:
  11.     explicit Vector2D(const T& x=0, const T& y=0) : x(x), y(y) {}
  12.     Vector2D(const Vector2D<T>& src) : x(src.x), y(src.y) {}
  13.     virtual ~Vector2D() {}
  14.  
  15.     // Accessors
  16.     inline T X() const { return x; }
  17.     inline T Y() const { return y; }
  18.     inline T X(const T& x) { this->x = x; }
  19.     inline T Y(const T& y) { this->y = y; }
  20.  
  21.     // Vector arithmetic
  22.     inline Vector2D<T> operator-() const
  23.         { return Vector2D<T>(-x, -y); }
  24.  
  25.     inline Vector2D<T> operator+() const
  26.         { return Vector2D<T>(+x, +y); }
  27.  
  28.     inline Vector2D<T> operator+(const Vector2D<T>& v) const
  29.         { return Vector2D<T>(x+v.x, y+v.y); }
  30.  
  31.     inline Vector2D<T> operator-(const Vector2D<T>& v) const
  32.         { return Vector2D<T>(x-v.x, y-v.y); }
  33.  
  34.     inline Vector2D<T> operator*(const T& s) const
  35.         { return Vector2D<T>(x*s, y*s); }
  36.  
  37.     // Dot product
  38.     inline T operator*(const Vector2D<T>& v) const
  39.         { return x*v.x + y*v.y; }
  40.  
  41.     // l-2 norm
  42.     inline T norm() const { return sqrt(x*x + y*y); }
  43.  
  44.     // inner angle (radians)
  45.     static T angle(const Vector2D<T>& v1, const Vector2D<T>& v2)
  46.     {
  47.         return acos( (v1 * v2) / (v1.norm() * v2.norm()) );
  48.     }
  49. };
  50.  
  51. int main()
  52. {
  53.     Vector2D<double> p1(215, 294);
  54.     Vector2D<double> p2(174, 228);
  55.     Vector2D<double> p3(303, 294);
  56.  
  57.     double rad = Vector2D<double>::angle(p2-p1, p3-p1);
  58.     double deg = rad * 180.0 / M_PI;
  59.  
  60.     std::cout << "rad = " << rad << "\tdeg = " << deg << std::endl;
  61.  
  62.     p1 = Vector2D<double>(153, 457);
  63.     p2 = Vector2D<double>(19, 457);
  64.     p3 = Vector2D<double>(15, 470);
  65.  
  66.     rad = Vector2D<double>::angle(p2-p1, p3-p1);
  67.     deg = rad * 180.0 / M_PI;
  68.  
  69.     std::cout << "rad = " << rad << "\tdeg = " << deg << std::endl;
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement