Skip to content

Instantly share code, notes, and snippets.

@lanserxt
Last active March 27, 2019 07:42
Show Gist options
  • Save lanserxt/c3fc616fc9582b92269c3f0d1dc10fa9 to your computer and use it in GitHub Desktop.
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/.
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