Skip to content

Instantly share code, notes, and snippets.

@BuckyI
Created December 23, 2023 07:30
Show Gist options
  • Save BuckyI/0709c7c1d0243c900e0208929ed32a7d to your computer and use it in GitHub Desktop.
Save BuckyI/0709c7c1d0243c900e0208929ed32a7d to your computer and use it in GitHub Desktop.
Complex number for C++
#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