Last active
May 7, 2020 22:55
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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