Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Swift tail-recursion experimentation: Recursive non-mutating implementation of Gregory-Leibnitz pi approximation.
// Recursive implementation
func LeibnizPiApproximationFunc(#afterIterations: Int) -> Double
{
// See http://stackoverflow.com/questions/24270693/nested-recursive-function-in-swift
var ApproxPi: (Double, Double, Double, Int) -> Double = { _ in return 0.0 }
ApproxPi =
{
(denom : Double, factor : Double, piAccum: Double, iteration: Int) -> Double in
if (iteration == 0)
{
return piAccum
}
return ApproxPi(denom + 2.0,
factor * -1.0,
piAccum + (factor * (4.0 / denom)),
iteration - 1)
}
return ApproxPi(3.0, -1.0, 4.0, afterIterations)
}
let i = 6000
println(LeibnizPiApproximationFunc(afterIterations: i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.