#ifndef COMPLEX_H #define COMPLEX_H 1 #include #include // Bad style! // using namespace std; class Complex { private: double re; // Real part double im; // Imaginary part // z = r*e^(i*phi) public: Complex(double x = 0., double y = 0.): re(x), im(y) {} // Bad style: // Complex(double x = 0., double y = 0.) { // re = x; im = y; // } // Destructor // ~Complex() {} /* // Copy constructor Complex(const Complex& z): re(z.a), im(z.b) {} */ /* // Copy coperator Complex& operator=(const Complex& z) { re = z.re; im = z.im; return *this; } */ static Complex polar(double r, double theta = 0.) { return Complex(r*cos(theta), r*sin(theta)); } double real() const { return re; } // double r = z.real(); void real(double r) { re = r; } // z.real(0.5); double imag() const { return im; } void imag(double i) { im = i; } double abs() const { return sqrt(re*re + im*im); } double norm() const { return re*re + im*im; } double arg() const { return atan2(im, re); } /*... // z = u + v; z = u.operator+(v); Complex operator+(const Complex& z) const { return Complex(re + z.re, im + z.im); } ...*/ Complex& operator+=(const Complex& z) { re += z.re; im += z.im; return *this; } Complex& operator-=(const Complex& z) { re -= z.re; im -= z.im; return *this; } Complex& operator*=(const Complex& z) { double r = re*z.re - im*z.im; double i = re*z.im + im*z.re; re = r; im = i; return *this; } Complex conj() const { return Complex(re, -im); } Complex inverse() const { double n = norm(); return Complex(re/n, -im/n); } Complex& operator/=(const Complex& z) { *this *= z.inverse(); return *this; } void roots(int n, Complex* root) const; }; inline Complex operator+( const Complex& u, const Complex& v ) { Complex res = u; res += v; return res; } inline Complex operator-( const Complex& u, const Complex& v ) { Complex res = u; res -= v; return res; } inline Complex operator*( const Complex& u, const Complex& v ) { Complex res = u; res *= v; return res; } inline Complex operator/( const Complex& u, const Complex& v ) { Complex res = u; res /= v; return res; } inline std::ostream& operator<<(std::ostream& s, const Complex& z) { s << z.real() << " + " << z.imag() << "*i"; return s; } inline std::istream& operator>>(std::istream& s, Complex& z) { double r, i; if (s >> r >> i) { z.real(r); z.imag(i); } return s; } #endif