Skip to content

Instantly share code, notes, and snippets.

@aclissold
Last active August 29, 2015 14:07
Show Gist options
  • Save aclissold/4e34e3269fc0139f932c to your computer and use it in GitHub Desktop.
Save aclissold/4e34e3269fc0139f932c to your computer and use it in GitHub Desktop.
e^x to n terms of accuracy http://swiftstub.com/71611885/
// Computes an estimation of e^x using a Taylor series expansion with n terms.
// 1 + (x^1/1!) + (x^2/2!) + ... + (x^n/n!)
func exponential(x: Double, n: Double) -> Double {
var exponential: Double = 1
for var y: Double = 1; y <= n; y++ {
var power: Double = 1
var yFactorial: Double = 1
for var i: Double = 1; i <= y; i++ {
yFactorial *= i
}
exponential += (pow(x, y)/yFactorial)
}
return exponential
}
// 2.718281828459045235360287471352662497757247093699959574966967...
println(exponential(1, 17)) // right at the cut-off point for accuracy
// 20.08553692318766774092852965458171789698790783855415014437893...
println(exponential(3, 20))
println("\n")
// 148.4131591025766034211155800405522796234876675938789890467528...
for numterms in [1, 2, 3, 5, 10, 20] as [Double] {
println(exponential(5, numterms))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment