The function shown below performs element-wise addition of two vectors. The vectors are arrays containing integer values of type Int
. The printed output of the result is [5, 7, 9, 11, 13]
. I am only showing addition here but I also have similar functions for subtraction, multiplication, and division of integer arrays.
func add(_ a: [Int], _ b: [Int]) -> [Int] {
var vec = [Int](repeating: 0, count: a.count)
for i in 0..<a.count {
vec[i] = a[i] + b[i]
}
return vec
}
let a = [1, 2, 3, 4, 5]
let b = [4, 5, 6, 7, 8]
let c = add(a, b)
print(c)
I noticed that Accelerate has some functions for performing integer arithmetic (see here). However, these functions operate on Int32
values instead of Int
. So I have to convert the integer arrays to Int32
before I can use the Accelerate functions. See below for an example.
import Accelerate
func add(_ a: [Int], _ b: [Int]) -> [Int] {
let x = a.map { Int32($0) }
let y = b.map { Int32($0) }
var z = [Int32](repeating: 0, count: x.count)
vDSP_vaddi(x, 1, y, 1, &z, 1, vDSP_Length(x.count))
let vec = z.map { Int($0) }
return vec
}
let a = [1, 2, 3, 4, 5]
let b = [4, 5, 6, 7, 8]
let c = add(a, b)
print(c)
I have several questions related to this:
- Is there a better way to convert the
Int
arrays to be compatible with Accelerate functions? Or should I just stick with my original function and do the integer arithmetic without Accelerate? - Why doesn't Accelerate have functions that support other integer types like
Int
,Int16
, andInt128
? - Instead of doing integer arithmetic, should I just do these operations with floating point values such as
Float
orDouble
then convert the final result to integer values?