complex.cpp

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.2 kB
4
Indexable
Never
// complex.cpp

#include <iostream>
#include <string>
#include <cmath>

#include "./complex.h"



Complex::Complex(float real, float imag) {
    m_real = real;
    m_imag = imag;
}

float Complex::getReal() { return m_real; }
float Complex::getImag() { return m_imag; }

bool Complex::isReal() { return m_imag == 0; }
bool Complex::isImag() { return m_real == 0; }

bool Complex::equals(Complex c) {
    return m_real==c.getReal() && m_imag==c.getImag();
}

Complex Complex::add(Complex c) { 
    return Complex(m_real + c.getReal(),
    m_imag + c.getImag());
}

Complex Complex::subtract(Complex c) {
    return Complex(this->m_real - c.getReal(),
    m_imag - c.getImag());
}

Complex Complex::multiply(Complex c) {
    // (a+bi)(c+di)=ac + adi + bci - bd

    // ac - bd
    float r = (m_real * c.getReal()) - (m_imag * c.getImag());
    
    // i(ad + bc)
    float i = (m_real * c.getImag()) + (m_imag * c.getReal()) ;
    return Complex(r, i);
}

Complex Complex::divide(Complex c) {
    // (a+bi)/(c+di)=(a+bi)(c-di)/(c^2+d^2)
    // nominator (a+bi)(c-di) = ac -adi + bci + bd

    // denominator: c+d
    float d = pow(c.getReal(), 2) + pow(c.getImag(), 2);

    // nominator real: ac + bd
    float r = (m_real * c.getReal()) + (m_imag * c.getImag());
    
    // nominator imaginary: bci - adi
    float i =  (m_imag * c.getReal()) - (m_real * c.getImag()) ;
    return Complex(r/d, i/d);
}


void Complex::print() {
    std::cout << *this;
}

std::string Complex::toString() {
    return std::to_string(this->m_real) 
            + ( this->m_real > 0 ? "+" : "") 
            + std::to_string(this->m_real) 
            + "i";
}



Complex Complex::operator+(const Complex &right) { return this->add(right); }
Complex Complex::operator-(const Complex &right) { return this->subtract(right); }
Complex Complex::operator*(const Complex &right) { return this->multiply(right); }
Complex Complex::operator/(const Complex &right) { return this->divide(right); }
bool Complex::operator==(const Complex &right)   { return this->equals(right); }
std::ostream& operator<<(std::ostream& out, Complex* c) { 
    out << c->toString();
    return out;    
}