Facebook
From Twoja stara słoń, 5 Years ago, written in C++.
Embed
Download Paste or View Raw
Hits: 241
  1. #ifndef __Complex_H__
  2. #define __Complex_H__
  3. #include <iostream>
  4. #include <math.h>
  5.  
  6. using namespace std;
  7.  
  8. class Complex
  9. {
  10. private:
  11.   double Real, Imag;
  12. public:
  13.   Complex (double Real=0, double Imag=0)
  14.   {
  15.     this->Real = Real;
  16.     this->Imag = Imag;
  17.   };
  18.  
  19.   Complex & operator= (const Complex & s)
  20.   {
  21.     Real = s.Real;
  22.     Imag = s.Imag;
  23.     return *this;
  24.   };
  25.  
  26.   Complex operator- () const
  27.   {
  28.     return Complex(-Real,-Imag);
  29.   };
  30.  
  31.   Complex & operator= (double co)
  32.   {
  33.     Real = co;
  34.     Imag = 0;
  35.     return *this;
  36.   };
  37.  
  38.   Complex operator+ (const Complex& co) const
  39.   {
  40.     Complex n;
  41.     n.Real = this->Real + co.Real;
  42.     n.Imag = this->Imag + co.Imag;
  43.     return n;
  44.   };
  45.  
  46.  
  47.   Complex & operator-= (Complex co)
  48.   {
  49.     Real -= co.Real;
  50.     Imag -= co.Imag;
  51.     return *this;
  52.   };
  53.  
  54.   friend Complex operator- (Complex, Complex);
  55.   friend ostream & operator << (ostream & s, const Complex & c)
  56.   {
  57.     s << "(" << c.Real << "," << c.Imag << ")";
  58.     return s;
  59.   };
  60.   Complex operator/ (const Complex co)
  61.   {
  62.     return Complex((this->Real*co.Real + this->Imag*co.Imag)/(co.Real*co.Real+co.Imag*co.Imag),
  63.                     (this->Imag*co.Real - this->Real*co.Imag)/(co.Real*co.Real + co.Imag*co.Imag));
  64.   };
  65.   Complex& operator/=(const Complex co){
  66.     Complex n;
  67.     n.Real = (Real*co.Real + Imag*co.Imag)/(co.Real*co.Real+co.Imag*co.Imag);
  68.     n.Imag = (Imag*co.Real - Real*co.Imag)/(co.Real*co.Real + co.Imag*co.Imag);
  69.     Real = n.Real;
  70.     Imag = n.Imag;
  71.     return *this;
  72.   };
  73.   double abs(){
  74.       return sqrt(this->Real*this->Real+this->Imag*this->Imag);
  75.   };
  76.   double phase(){
  77.       if(this->Real > 0){
  78.           return atan(1/(this->Imag/this->Real));
  79.       }
  80.       if ( this->Real < 0 ){
  81.           return atan(1/(this->Imag/this->Real))+M_PI;
  82.       }
  83.       if( this->Imag > 0 ){
  84.           return M_PI/2;
  85.       }
  86.       return -M_PI/2;
  87.   };
  88.   Complex conj(){
  89.       Complex n;
  90.       n.Real = this->Real;
  91.       n.Imag = -this->Imag;
  92.       return n;
  93.   };
  94. };
  95.  
  96. inline Complex
  97. operator - (Complex s1, Complex s2)
  98. {
  99.   Complex n (s1);
  100.   return n -= s2;
  101. }
  102.  
  103. #endif /* __Complex_H__ */
  104.