Swift 中复向量的乘法

Multiplication of complex vectors in Swift

我有两个复向量:

a = [(0.5 + 2.0i), (-1.0 - 3.0i), (-3.0 + 1.5i)]

b = [(-0.5 - 2.2i), (1.3 + 2.0i), (3.0 - 2.5i)]

In Matlab, c = a.*b

也就是说,两个复向量的逐个元素相乘得到:

c = [(4.15 - 2.1i), (4.7 - 5.9i), (-5.25 + 12.0i)]

通常,在 Swift 中,我在单独的数组中表示复向量的实部和虚部。

所以,

let aReal = [0.5, -1.0, -3.0]

let bReal = [-0.5, 1.3, 3.0]

let aImag = [2.0, -3.0, 1.5]

let bImag = [-2.2, 2.0, -2.5]

基于上面的乘法,在Swift中,我希望得到:

// cReal = [4.15, 4.7, -5.25]

// cImag = [-2.1, -5.9, 12.0]

这取决于你用它们做什么,但我会用 * 运算符定义一个 Complex 类型。例如在 Swift 3:

struct Complex<T: FloatingPoint> {
    let real: T
    let imaginary: T

    static func +(lhs: Complex<T>, rhs: Complex<T>) -> Complex<T> {
        return Complex(real: lhs.real + rhs.real, imaginary: lhs.imaginary + rhs.imaginary)
    }

    static func -(lhs: Complex<T>, rhs: Complex<T>) -> Complex<T> {
        return Complex(real: lhs.real - rhs.real, imaginary: lhs.imaginary - rhs.imaginary)
    }

    static func *(lhs: Complex<T>, rhs: Complex<T>) -> Complex<T> {
        return Complex(real: lhs.real * rhs.real - lhs.imaginary * rhs.imaginary,
                       imaginary: lhs.imaginary * rhs.real + lhs.real * rhs.imaginary)
    }
}

// you can print it any way you want, but I'd probably do:

extension Complex: CustomStringConvertible {
    var description: String {
        switch (real, imaginary) {
        case (_, 0):
            return "\(real)"
        case (0, _):
            return "\(imaginary)i"
        case (_, let b) where b < 0:
            return "\(real) - \(abs(imaginary))i"
        default:
            return "\(real) + \(imaginary)i"
        }
    }
}

然后您可以使用 zipmap 获取两个数组并从两个数组中获取各自的值执行一些计算:

let a = [Complex<Double>(real: 0.5, imaginary: 2.0), Complex<Double>(real: -1.0, imaginary: -3.0), Complex<Double>(real: -3.0, imaginary: 1.5)]
let b = [Complex<Double>(real: -0.5, imaginary: -2.2), Complex<Double>(real: 1.3, imaginary: 2.0), Complex<Double>(real: 3.0, imaginary: -2.5)]

let c = zip(a, b).map { [=11=] *  }

print(c)

那就是:

[4.15 - 2.1i, 4.7 - 5.9i, -5.25 + 12.0i]

或者,如果您确实有单独的数组,请先将它们转换为 [Complex]

let aReal = [0.5, -1.0, -3.0]
let aImag = [2.0, -3.0, 1.5]

let bReal = [-0.5, 1.3, 3.0]
let bImag = [-2.2, 2.0, -2.5]

let a = zip(aReal, aImag).map { Complex<Double>(real: [=12=], imaginary: ) }
let b = zip(bReal, bImag).map { Complex<Double>(real: [=12=], imaginary: ) }

let c = zip(a, b).map { [=12=] *  }
print(c)