-
Notifications
You must be signed in to change notification settings - Fork 68
/
Complex.hpp
110 lines (87 loc) · 2.55 KB
/
Complex.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include <ostream>
#include <cmath>
template <typename T=float>
class Complex_t {
public:
Complex_t() = default;
Complex_t(T r, T i) : m_r(r), m_i(i) {}
T real() const { return m_r; }
T imaginary() const { return m_i; }
T norm_sqr() const {
return m_r * m_r + m_i * m_i;
}
T norm() const {
return std::sqrt(norm_sqr());
}
Complex_t& operator+=(const Complex_t& other) {
m_r += other.m_r;
m_i += other.m_i;
return *this;
}
Complex_t& operator-=(const Complex_t& other) {
m_r -= other.m_r;
m_i -= other.m_i;
return *this;
}
Complex_t& operator*=(const Complex_t& other) {
const auto r = m_r * other.m_r - m_i * other.m_i;
const auto i = m_r * other.m_i + m_i * other.m_r;
m_r = r;
m_i = i;
return *this;
}
Complex_t& operator*=(T factor) {
m_r *= factor;
m_i *= factor;
return *this;
}
Complex_t& operator/=(const Complex_t& other) {
const T ns = other.norm_sqr();
const auto r = (m_r * other.m_r + m_i * other.m_i) / ns;
const auto i = (m_i * other.m_r - m_r * other.m_i) / ns;
m_r = r;
m_i = i;
return *this;
}
Complex_t& operator/=(T divisor) {
m_r /= divisor;
m_i /= divisor;
return *this;
}
friend Complex_t operator+(Complex_t a, const Complex_t& b) {
return a += b;
}
friend Complex_t operator-(Complex_t a, const Complex_t& b) {
return a -= b;
}
friend Complex_t operator*(Complex_t a, const Complex_t& b) {
return a *= b;
}
friend Complex_t operator*(Complex_t c, T factor) {
return c *= factor;
}
friend Complex_t operator*(T factor, Complex_t c) {
return c *= factor;
}
friend Complex_t operator/(Complex_t a, Complex_t b) {
return a /= b;
}
friend Complex_t operator/(Complex_t c, T divisor) {
return c /= divisor;
}
friend Complex_t operator/(T dividend, const Complex_t& c) {
return Complex_t(dividend, 0) / c;
}
friend bool operator==(const Complex_t& a, const Complex_t& b) {
return a.m_r == b.m_r && a.m_i == b.m_i;
}
friend bool operator<(const Complex_t& a, const Complex_t& b) {
return a.norm_sqr() < b.norm_sqr();
}
friend std::ostream& operator<<(std::ostream& os, const Complex_t<T>& c) {
return os << "(" << c.real() << ", " << c.imaginary() << ")";
}
private:
T m_r{}, m_i{};
};
using Complex = Complex_t<>;