tiom4eg

point/vec2

Apr 21st, 2022 (edited)
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #define int long long
  2. #define ld long double
  3. const ld EPS = 1e-12, PI = 3.1415926535897;
  4.  
  5. // geometry primitives
  6. int sign(int x) {
  7.     if (x > 0) return 1;
  8.     if (x < 0) return -1;
  9.     return 0;
  10. }
  11. int sign(ld x) {
  12.     if (x > EPS) return 1;
  13.     if (x < -EPS) return -1;
  14.     return 0;
  15. }
  16. ld sq(ld x) { return x * x; }
  17.  
  18. #define vec2 point
  19. struct point {
  20.     ld x, y;
  21.     point() : x(), y() {} // empty constructor
  22.     point(const ld& x_, const ld& y_) : x(x_), y(y_) {} // constructor from coords
  23.     point operator-(const point& oth) const { return point(x - oth.x, y - oth.y); } // various operators
  24.     point operator+(const point& oth) const { return point(x + oth.x, y + oth.y); }
  25.     point operator*(const ld& a) const { return point(x * a, y * a); }
  26.     ld operator^(const point& oth) const { return x * oth.y - y * oth.x; } // scalar multiplication
  27.     bool operator<(const point& oth) const { // check, if point equal
  28.         if (sign(x - oth.x)) return x < oth.x;
  29.         if (sign(y - oth.y)) return y < oth.y;
  30.         return false;
  31.     }
  32.     bool operator==(const point& oth) const { return !sign(x - oth.x) && !sign(y - oth.y);  }
  33.     ld len2() const { return sq(x) + sq(y); } // len of the vector squared (if we don't need precision)
  34.     ld len() const { return sqrt(len2()); } // len of the vector
  35.     point norm() const { // norm a vector
  36.         ld d = len();
  37.         assert(sign(d)); // we can't norm a point
  38.         return point(x / d, y / d);
  39.     }
  40.     point ort() const { return point(-y, x); } // orthogonal vector
  41.     void print() { cout << '(' << x << ',' << y << ')' << endl; }
  42. };  
Add Comment
Please, Sign In to add comment