Hi All,
I'm new to Swift and was exploring the language today by generating random numbers from a normal distribution. The performance of my code is noticeably slower than similar code that I had previously written in Chez Scheme. Are there any obvious performance pitfalls in the way I've written this code?
Thanks,
Travis
import Foundation
// rejection method from https://www.cse.wustl.edu/~jain/books/ftp/ch5f_slides.pdf
func rnorm(_ mu: Double = 0, _ sd: Double = 1) -> Double {
func comp(_ x: Double) -> Double {
return exp(-1 * pow(x-1, 2)/2)
}
var u1: Double; var u2: Double; var x: Double;
repeat {
u1 = Double.random(in: 0...1)
u2 = Double.random(in: 0...1)
x = -1 * log(u1)
} while u2 > comp(x)
if Double.random(in: 0...1) > 0.5{
return (mu + sd * x)
} else {
return (mu - sd * x)
}
}
func sampleNormal(_ n: Int, _ mu: Double = 0, _ sd: Double = 1) -> [Double] {
var out = Array(repeating: 0.0, count: n)
for i in 1..<n {
out[i] = rnorm(mu, sd)
}
return out
}
let x = sampleNormal(1000000, 10, 10)
print(x.reduce(0, +)/Double(x.count))