// Functions for TwoVector class, polor coord. version // Glen Cowan, RHUL Physics Dept., October 2004 #include #include #include "TwoVector.h" using namespace std; // constructors TwoVector::TwoVector(){ // default is unit vector along x m_r = 1; m_theta = 0; } TwoVector::TwoVector (double x, double y){ m_r = sqrt(x*x + y*y); m_theta = atan2(y,x); } // getter-like functions (const, since object's state unchanged) double TwoVector::x() const { return this->r() * this->cosTheta(); } double TwoVector::y() const { return this->r() * this->sinTheta(); } double TwoVector::r() const { return fabs(m_r); } double TwoVector::cosTheta() const { return cos(m_theta); } double TwoVector::sinTheta() const { return sin(m_theta); } double TwoVector::theta() const { double theta = m_theta; if ( theta < 0 || theta > 2.*M_PI ) { double x = this->x(); double y = this->y(); theta = atan2 (y, x); } return theta; } // setter-like functions void TwoVector::set(double x, double y) { m_r = sqrt(x*x + y*y); m_theta = atan2(y, x); } void TwoVector::setX(double x) { double y = this->y(); m_r = sqrt(x*x + y*y); m_theta = atan2(y, x); } void TwoVector::setY(double y) { double x = this->x(); m_r = sqrt(x*x + y*y); m_theta = atan2(y, x); } void TwoVector::setR(double r) { m_r = r; } void TwoVector::setTheta(double t) { m_theta = t; } void TwoVector::rotate(double alpha) { m_theta += alpha; } // operators overloaded as member functions TwoVector TwoVector::operator+(const TwoVector& b) { double cx = this->x() + b.x(); double cy = this->y() + b.y(); TwoVector c(cx, cy); return c; } TwoVector TwoVector::operator-(const TwoVector& b) { double cx = this->x() - b.x(); double cy = this->y() - b.y(); TwoVector c(cx, cy); return c; } TwoVector& TwoVector::operator+=(const TwoVector& b) { double cx = this->x() + b.x(); double cy = this->y() + b.y(); this->setX(cx); this->setY(cy); return *this; } TwoVector& TwoVector::operator-=(const TwoVector& b) { double cx = this->x() - b.x(); double cy = this->y() - b.y(); this->setX(cx); this->setY(cy); return *this; } // non-member operators and functions TwoVector operator*(const TwoVector& a, double b) { double cx = a.x()*b; double cy = a.y()*b; TwoVector c(cx, cy); return c; } TwoVector operator*(double b, const TwoVector& a) { double cx = a.x()*b; double cy = a.y()*b; TwoVector c(cx, cy); return c; } double dot(const TwoVector & a, const TwoVector & b) { double dotVal = a.x()*b.x() + a.y()*b.y(); return dotVal; } TwoVector rotate(const TwoVector& a, double alpha) { double newTheta = a.theta() + alpha; double r = a.r(); TwoVector b (r, 0); // create with right length b.setTheta(newTheta); return b; }