Created
December 23, 2023 07:30
-
-
Save BuckyI/0709c7c1d0243c900e0208929ed32a7d to your computer and use it in GitHub Desktop.
Complex number for C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdexcept> | |
#include <cmath> | |
namespace complex_numbers | |
{ | |
class Complex | |
{ | |
private: | |
double _real; | |
double _imag; | |
public: | |
Complex(double real, double imag) : _real(real), _imag(imag){}; | |
double real() const { return this->_real; } | |
double imag() const { return this->_imag; } | |
double abs() const { return std::sqrt(std::pow(this->_real, 2) + std::pow(this->_imag, 2)); } | |
Complex conj() const { return Complex(this->_real, -1 * this->_imag); } | |
Complex exp() const | |
{ | |
double k = std::exp(this->_real); | |
return Complex(k * std::cos(this->_imag), k * std::sin(this->_imag)); | |
} | |
Complex operator+(const Complex &other) const { return Complex(_real + other.real(), _imag + other.imag()); } | |
Complex operator-(const Complex &other) const { return Complex(_real - other.real(), _imag - other.imag()); } | |
Complex operator*(const Complex &other) const | |
{ | |
double a{_real}, b{_imag}, c{other.real()}, d{other.imag()}; | |
return Complex(a * c - b * d, b * c + a * d); | |
} | |
Complex operator/(const Complex &other) const | |
{ | |
// only for non-zero complex number | |
if (other.abs() == 0) | |
throw std::domain_error("only for non-zero complex number"); | |
double a{_real}, b{_imag}, c{other.real()}, d{other.imag()}; | |
return Complex((a * c + b * d) / (c * c + d * d), (b * c - a * d) / (c * c + d * d)); | |
} | |
}; | |
} // namespace complex_numbers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment