std.math.Complex: add 'negation' and 'mulitply by i'

This commit is contained in:
BlueAlmost 2022-03-27 10:54:43 +02:00 committed by GitHub
parent 7ae22813ee
commit 406507c6dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -88,6 +88,22 @@ pub fn Complex(comptime T: type) type {
};
}
/// Returns the negation of a complex number.
pub fn neg(self: Self) Self {
return Self{
.re = -self.re,
.im = -self.im,
};
}
/// Returns the product of complex number and i=sqrt(-1)
pub fn mulbyi(self: Self) Self {
return Self{
.re = -self.im,
.im = self.re,
};
}
/// Returns the reciprocal of a complex number.
pub fn reciprocal(self: Self) Self {
const m = self.re * self.re + self.im * self.im;
@ -146,6 +162,20 @@ test "complex.conjugate" {
try testing.expect(c.re == 5 and c.im == -3);
}
test "complex.neg" {
const a = Complex(f32).init(5, 3);
const c = a.neg();
try testing.expect(c.re == -5 and c.im == -3);
}
test "complex.mulbyi" {
const a = Complex(f32).init(5, 3);
const c = a.mulbyi();
try testing.expect(c.re == -3 and c.im == 5);
}
test "complex.reciprocal" {
const a = Complex(f32).init(5, 3);
const c = a.reciprocal();