Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cpp Program to the “classical user-defined arithmetic type” -- complex.
// Program to the “classical user-defined arithmetic type” -- complex.
// Note: my "complex"; not the one from the standard library
#include<iostream>
#include<cmath>
class complex{
double re, im; // representation: two doubles
public:
complex(double r, double i): re{r}, im{i} {}; // construct complex from two scalars
complex(double r): re{r}, im{0}{}; // construct complex from one scalar
complex(): re{0}, im{0}{}; // default complex: {0,0}
double real() const { return re; }
void real(double r){ re = r; }
double imag() const { return im; }
void imag(double i){ im = i; }
complex& operator+= (const complex x) {
re+=x.re; // add to re and im
im+=x.im;
return *this; // and return the result
}
complex& operator-= (const complex x) {
re-=x.re;
im-=x.im;
return *this;
}
complex& operator*=(complex); // defined out-of-class
complex& operator/=(complex);
};
complex& complex::operator*= (const complex x){
auto temp = re;
re = re * x.real() - im * x.imag(); // (a+bi)(c+di)=(ac-bd)+(bc+ad)i
im = im * x.real() + temp * x.imag();
return *this;
}
complex& complex::operator/= (const complex x){
auto temp = re;
auto denominator = pow(x.real(), 2) + pow(x.imag(),2);
re = (re * x.real() + im * x.imag()) / (denominator); // (a+bi)/(c+di)= (ac+bd)/(c^2+d^2) + (bc-ad)/(c^2+d^2)i
im = (im* x.real() - temp * x.imag()) / (denominator);
return *this;
}
complex operator+(complex a, complex b) { return a+=b; }
complex operator-(complex a, complex b) { return a-=b; }
complex operator-(complex a) { return {-a.real(), -a.imag()}; } // unary minus
complex operator*(complex a, complex b) { return a*=b; }
complex operator/(complex a, complex b) { return a/=b; }
bool operator==(complex a, complex b){ // equal
return a.real()==b.real() && a.imag()==b.imag();
}
bool operator!=(complex a, complex b) // not equal
{
return !(a==b);
}
std::ostream& operator<<(std::ostream&s, const complex& z)
{
return s << '(' << z.real() << ',' << z.imag() << ')';
}
void test_complex(){
auto a = complex(1);
std::cout << "a = " << a << std::endl;
auto b = complex(2,3.3);
std::cout << "old b = " << b << std::endl;
b.imag(2.2);
std::cout << "b = " << b << std::endl;
}
void test_complex_mul(){
auto a = complex(3,2);
auto b = complex(1,7);
std::cout << "a * b = " << a * b << std::endl; // (−11 + 23i)
}
void test_complex_div(){
auto a = complex(2,3);
auto b = complex(4,5);
std::cout << "a / b = " << a/b << std::endl; // (0.560976,0.0487805)
}
int main(){
test_complex();
test_complex_mul();
test_complex_div();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment