std.Complex: use better arg passing convention and fix a TODO

master
Andrew Kelley 2018-06-16 21:32:53 -04:00
parent 751518787a
commit 06a26f0965
2 changed files with 11 additions and 12 deletions

View File

@ -37,28 +37,28 @@ pub fn Complex(comptime T: type) type {
};
}
pub fn add(self: *const Self, other: *const Self) Self {
pub fn add(self: Self, other: Self) Self {
return Self{
.re = self.re + other.re,
.im = self.im + other.im,
};
}
pub fn sub(self: *const Self, other: *const Self) Self {
pub fn sub(self: Self, other: Self) Self {
return Self{
.re = self.re - other.re,
.im = self.im - other.im,
};
}
pub fn mul(self: *const Self, other: *const Self) Self {
pub fn mul(self: Self, other: Self) Self {
return Self{
.re = self.re * other.re - self.im * other.im,
.im = self.im * other.re + self.re * other.im,
};
}
pub fn div(self: *const Self, other: *const Self) Self {
pub fn div(self: Self, other: Self) Self {
const re_num = self.re * other.re + self.im * other.im;
const im_num = self.im * other.re - self.re * other.im;
const den = other.re * other.re + other.im * other.im;
@ -69,14 +69,14 @@ pub fn Complex(comptime T: type) type {
};
}
pub fn conjugate(self: *const Self) Self {
pub fn conjugate(self: Self) Self {
return Self{
.re = self.re,
.im = -self.im,
};
}
pub fn reciprocal(self: *const Self) Self {
pub fn reciprocal(self: Self) Self {
const m = self.re * self.re + self.im * self.im;
return Self{
.re = self.re / m,
@ -84,7 +84,7 @@ pub fn Complex(comptime T: type) type {
};
}
pub fn magnitude(self: *const Self) T {
pub fn magnitude(self: Self) T {
return math.sqrt(self.re * self.re + self.im * self.im);
}
};

View File

@ -4,18 +4,17 @@ const math = std.math;
const cmath = math.complex;
const Complex = cmath.Complex;
// TODO when #733 is solved this can be @typeOf(z) instead of Complex(@typeOf(z.re))
pub fn sqrt(z: var) Complex(@typeOf(z.re)) {
pub fn sqrt(z: var) @typeOf(z) {
const T = @typeOf(z.re);
return switch (T) {
f32 => sqrt32(z),
f64 => sqrt64(z),
else => @compileError("sqrt not implemented for " ++ @typeName(z)),
else => @compileError("sqrt not implemented for " ++ @typeName(T)),
};
}
fn sqrt32(z: *const Complex(f32)) Complex(f32) {
fn sqrt32(z: Complex(f32)) Complex(f32) {
const x = z.re;
const y = z.im;
@ -57,7 +56,7 @@ fn sqrt32(z: *const Complex(f32)) Complex(f32) {
}
}
fn sqrt64(z: *const Complex(f64)) Complex(f64) {
fn sqrt64(z: Complex(f64)) Complex(f64) {
// may encounter overflow for im,re >= DBL_MAX / (1 + sqrt(2))
const threshold = 0x1.a827999fcef32p+1022;