gpt4 book ai didi

arrays - Swift 中复杂向量的乘法

转载 作者:搜寻专家 更新时间:2023-11-01 07:16:27 24 4
gpt4 key购买 nike

我有两个复向量:

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 { $0 * $1 }

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: $0, imaginary: $1) }
let b = zip(bReal, bImag).map { Complex<Double>(real: $0, imaginary: $1) }

let c = zip(a, b).map { $0 * $1 }
print(c)

关于arrays - Swift 中复杂向量的乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41974764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com