Skip to content

Instantly share code, notes, and snippets.

@jbagley
Last active May 7, 2020 22:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbagley/2a28d09c02a7c391c0ee to your computer and use it in GitHub Desktop.
Save jbagley/2a28d09c02a7c391c0ee to your computer and use it in GitHub Desktop.
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