#ifndef _COMPLEX_H #define _COMPLEX_H #include #include class Complex { private: double re, im; public: Complex( double, double ); // Accessors double real() const; double imag() const; double abs() const; Complex exp() const; // Mutators void normalize(); friend std::ostream & operator << ( std::ostream &, const Complex & ); }; // Constructor Complex::Complex( double r, double i ):re(r), im(i) { // empty constructor } // return the real component double Complex::real() const { return re; } // return the imaginary component double Complex::imag() const { return im; } // return the absolute value double Complex::abs() const { return sqrt( re*re + im*im ); } // return the exponential of the complex value Complex Complex::exp() const { double exp_re = std::exp( re ); return Complex( exp_re*std::cos(im), exp_re*std::sin(im) ); } // normalize the complex number (giving it unit norm, |z| = 1) void Complex::normalize() { if ( re == 0 && im == 0 ) { return; } double absval = abs(); re /= absval; im /= absval; } std::ostream & operator << ( std::ostream & out, const Complex & z ) { if ( z.im > 0 ) { if ( z.re == 0 ) { out << z.im << 'j'; // 4j } else { out << z.re << " + " << z.im << 'j'; // 3 + 4j } } else if ( z.im == 0 ) { out << z.re; // 3 } else { // z.im < 0 if ( z.re == 0 ) { out << z.im << 'j'; // -4j } else { out << z.re << " - " << (-z.im) << 'j'; // 3 - 4j } } return out; } #endif