如何使用 vDSP / Accelerate in swift for iOS 逐元素计算向量的平方根
How to compute the square root of a vector elementwise using vDSP / Accelerate in swift for iOS
我有一个类似于 [Float](repeating: 1.0, count: 42000)
的向量,我想使用 Accelerate 框架计算每个元素的平方根,但不存在与 vDSP_vsqrt
中所述相反的函数=14=]。我应该怎么做?
似乎正确的调用函数是 vvsqrtf
来自 vForce
。
这里是 the documentation 的例子,它的用法:
var x: [Float] = [100, 10000, 64, 144]
var y = [Float](repeating: 0, count: x.count)
var n = Int32(x.count)
vvsqrtf(&y, &x, &n)
print(y) // [10.0, 100.0, 8.0, 12.0]
请注意,您还可以计算平方根 "in place" :
var data = [Float](repeating: 25.0, count: input.count)
let n = Int32(data.count)
vvsqrtf(&data, data, &n)
我建议制作辅助函数来包装 vvsqrtf
,以公开更 Swift 友好的 API:
import Accelerate
extension Array where Element == Float {
func squareRootedElements() -> [Float] {
if self.isEmpty { return [] }
var output = Array(repeating: 0, count: self.count)
var count = Int32(self.count)
vvsqrtf(&output, self, &count)
return output
}
mutating func squareRootElements() {
if self.isEmpty { return }
var count = Int32(self.count)
vvsqrtf(&self, self, &count)
}
}
var squares = stride(from: 0 as Float, through: 10, by: +1).map { [=10=] * [=10=] }
print(squares)
print(squares.squareRootedElements())
vForce Swift 覆盖使语法更简单:
vForce.sqrt(vector: AccelerateBuffer)
看看:https://github.com/apple/swift/blob/master/stdlib/public/Darwin/Accelerate/vForce_Operations.swift
...和...
我有一个类似于 [Float](repeating: 1.0, count: 42000)
的向量,我想使用 Accelerate 框架计算每个元素的平方根,但不存在与 vDSP_vsqrt
中所述相反的函数=14=]。我应该怎么做?
似乎正确的调用函数是 vvsqrtf
来自 vForce
。
这里是 the documentation 的例子,它的用法:
var x: [Float] = [100, 10000, 64, 144]
var y = [Float](repeating: 0, count: x.count)
var n = Int32(x.count)
vvsqrtf(&y, &x, &n)
print(y) // [10.0, 100.0, 8.0, 12.0]
请注意,您还可以计算平方根 "in place" :
var data = [Float](repeating: 25.0, count: input.count)
let n = Int32(data.count)
vvsqrtf(&data, data, &n)
我建议制作辅助函数来包装 vvsqrtf
,以公开更 Swift 友好的 API:
import Accelerate
extension Array where Element == Float {
func squareRootedElements() -> [Float] {
if self.isEmpty { return [] }
var output = Array(repeating: 0, count: self.count)
var count = Int32(self.count)
vvsqrtf(&output, self, &count)
return output
}
mutating func squareRootElements() {
if self.isEmpty { return }
var count = Int32(self.count)
vvsqrtf(&self, self, &count)
}
}
var squares = stride(from: 0 as Float, through: 10, by: +1).map { [=10=] * [=10=] }
print(squares)
print(squares.squareRootedElements())
vForce Swift 覆盖使语法更简单:
vForce.sqrt(vector: AccelerateBuffer)
看看:https://github.com/apple/swift/blob/master/stdlib/public/Darwin/Accelerate/vForce_Operations.swift
...和...