I'm trying to create a Swift function that creates an array of random numbers similar to the numpy.random.rand function in the NumPy package.
This example creates a large NumPy array with random numbers. I am using uv to run the Python code.
# Run with -> uv run main.py
import numpy as np
def main():
n = 100_000_000
a = np.random.rand(n)
print("first value is", a[0])
print("last value is", a[n - 1])
if __name__ == "__main__":
main()
Here is my attempt to do the same thing in Swift.
// Build with -> swiftc main.swift -Ounchecked
// Run with -> ./main
func randomArray(_ count: Int) -> [Double] {
let result = Array<Double>(unsafeUninitializedCapacity: count) { buffer, initCount in
for i in 0..<count {
buffer[i] = Double.random(in: 0...1)
}
initCount = count
}
return result
}
func main() {
let n = 100_000_000
let a = randomArray(n)
print("first value is \(a[0])")
print("last value is \(a[n - 1])")
}
main()
The Swift code is much slower than the NumPy code. Is there a better way to create a random array in Swift? Does Accelerate provide any functions that could speed this up?