| ... | @@ -88,6 +88,22 @@ pub fn Complex(comptime T: type) type { | ... | @@ -88,6 +88,22 @@ pub fn Complex(comptime T: type) type { |
| 88 | }; | 88 | }; |
| 89 | } | 89 | } |
| 90 | | 90 | |
| | 91 | /// Returns the negation of a complex number. |
| | 92 | pub fn neg(self: Self) Self { |
| | 93 | return Self{ |
| | 94 | .re = -self.re, |
| | 95 | .im = -self.im, |
| | 96 | }; |
| | 97 | } |
| | 98 | |
| | 99 | /// Returns the product of complex number and i=sqrt(-1) |
| | 100 | pub fn mulbyi(self: Self) Self { |
| | 101 | return Self{ |
| | 102 | .re = -self.im, |
| | 103 | .im = self.re, |
| | 104 | }; |
| | 105 | } |
| | 106 | |
| 91 | /// Returns the reciprocal of a complex number. | 107 | /// Returns the reciprocal of a complex number. |
| 92 | pub fn reciprocal(self: Self) Self { | 108 | pub fn reciprocal(self: Self) Self { |
| 93 | const m = self.re * self.re + self.im * self.im; | 109 | const m = self.re * self.re + self.im * self.im; |
| ... | @@ -146,6 +162,20 @@ test "complex.conjugate" { | ... | @@ -146,6 +162,20 @@ test "complex.conjugate" { |
| 146 | try testing.expect(c.re == 5 and c.im == -3); | 162 | try testing.expect(c.re == 5 and c.im == -3); |
| 147 | } | 163 | } |
| 148 | | 164 | |
| | 165 | test "complex.neg" { |
| | 166 | const a = Complex(f32).init(5, 3); |
| | 167 | const c = a.neg(); |
| | 168 | |
| | 169 | try testing.expect(c.re == -5 and c.im == -3); |
| | 170 | } |
| | 171 | |
| | 172 | test "complex.mulbyi" { |
| | 173 | const a = Complex(f32).init(5, 3); |
| | 174 | const c = a.mulbyi(); |
| | 175 | |
| | 176 | try testing.expect(c.re == -3 and c.im == 5); |
| | 177 | } |
| | 178 | |
| 149 | test "complex.reciprocal" { | 179 | test "complex.reciprocal" { |
| 150 | const a = Complex(f32).init(5, 3); | 180 | const a = Complex(f32).init(5, 3); |
| 151 | const c = a.reciprocal(); | 181 | const c = a.reciprocal(); |