Last active
March 27, 2019 07:42
-
-
Save lanserxt/c3fc616fc9582b92269c3f0d1dc10fa9 to your computer and use it in GitHub Desktop.
Pi approximate calculation by Monte Carlo method. Inspired by https://www.weheartswift.com/random-pi/.
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
func piCalc(_ totalPoints: Int) -> Double { | |
var nPointsInside = 0 | |
for _ in 1...totalPoints { | |
let (x, y) = (drand48() * 2 - 1, drand48() * 2 - 1) | |
if x * x + y * y <= 1 { | |
nPointsInside += 1 | |
} | |
} | |
return 4.0 * Double(nPointsInside) / Double(totalPoints) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment