// Functions for TwoVector class // 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_x = 1; m_y = 0; } TwoVector::TwoVector (double x, double y){ m_x = x; m_y = y; } // getter-like functions (const, since object's state unchanged) double TwoVector::x() const { return m_x; } double TwoVector::y() const { return m_y; } double TwoVector::r() const { double rVal = sqrt(m_x*m_x + m_y*m_y); return rVal; } double TwoVector::cosTheta() const { double rVal = this->r(); double cosThetaVal; if ( rVal > 0 ) { cosThetaVal = m_x / rVal; } else { cosThetaVal = 1.0; } return cosThetaVal; } double TwoVector::sinTheta() const { double rVal = this->r(); double sinThetaVal; if ( rVal > 0 ) { sinThetaVal = m_y / rVal; } else { sinThetaVal = 0.0; } return sinThetaVal; } double TwoVector::theta() const { double thetaVal = atan2 (m_y, m_x); return thetaVal; } // setter-like functions void TwoVector::set(double x, double y) { m_x = x; m_y = y; } void TwoVector::setX(double x) { m_x = x; } void TwoVector::setY(double y) { m_y = y; } void TwoVector::setR(double r) { double c = this->cosTheta(); double s = this->sinTheta(); m_x = r * c; m_y = r * s; } void TwoVector::setTheta(double t) { double r = this->r(); m_x = r * cos(t); m_y = r * sin(t); } void TwoVector::rotate(double alpha) { double newTheta = this->theta() + alpha; double r = this->r(); m_x = r * cos(newTheta); m_y = r * sin(newTheta); } // operators overloaded as member functions TwoVector TwoVector::operator+(const TwoVector& b) { double cx = this->m_x + b.x(); double cy = this->m_y + b.y(); TwoVector c(cx, cy); return c; } TwoVector TwoVector::operator-(const TwoVector& b) { double cx = this->m_x - b.x(); double cy = this->m_y - b.y(); TwoVector c(cx, cy); return c; } TwoVector& TwoVector::operator+=(const TwoVector& b) { double cx = this->m_x + b.x(); double cy = this->m_y + b.y(); this->setX(cx); this->setY(cy); return *this; } TwoVector& TwoVector::operator-=(const TwoVector& b) { double cx = this->m_x - b.x(); double cy = this->m_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; }