5# define M_PI 3.14159265358979323846
11#include "include/complex_number.h"
12#include "include/numerical_methods.h"
21ComplexNumber::ComplexNumber(std::complex<double> val)
44 if (std::abs(other.value) < 1e-10) {
45 throw std::runtime_error(
"Division by zero complex number");
58 int exp = std::abs(n);
62 result = result * base;
80double ComplexNumber::magnitude()
const
82 return std::abs(value);
85double ComplexNumber::phase()
const
87 return std::arg(value);
97 if (std::abs(value) < 1e-10) {
98 throw std::runtime_error(
"Logarithm of zero");
123std::vector<ComplexNumber> ComplexNumber::rootsOfUnity(
int n)
126 throw std::runtime_error(
"n must be positive for roots of unity");
129 std::vector<ComplexNumber> roots;
130 double angle = 2.0 * M_PI / n;
132 for (
int k = 0; k < n; k++) {
133 double theta = k * angle;
134 roots.emplace_back(std::cos(theta), std::sin(theta));
140std::string ComplexNumber::toString()
const
142 std::ostringstream oss;
143 double real = value.real();
144 double imag = value.imag();
146 if (std::abs(imag) < 1e-10) {
148 }
else if (std::abs(real) < 1e-10) {
149 if (std::abs(imag - 1) < 1e-10) {
151 }
else if (std::abs(imag + 1) < 1e-10) {
159 if (std::abs(imag - 1) < 1e-10) {
162 oss <<
" + " << imag <<
"i";
165 if (std::abs(imag + 1) < 1e-10) {
168 oss <<
" - " << (-imag) <<
"i";
176std::string ComplexNumber::toPolarString()
const
178 double r = magnitude();
179 double theta = phase();
181 std::ostringstream oss;
182 oss << r <<
" * e^(i * " << theta <<
")";