Skip to content

Instantly share code, notes, and snippets.

@KelvinJin
Last active September 5, 2016 13:10
Show Gist options
  • Save KelvinJin/44f5d87c8a438c97236c90cce972d31e to your computer and use it in GitHub Desktop.
Save KelvinJin/44f5d87c8a438c97236c90cce972d31e to your computer and use it in GitHub Desktop.
Calculate Pi
import Foundation
srand48(Int(arc4random()))
func rand(from: Double, to: Double) -> Double {
assert(to - from > 0)
let seed = drand48()
return seed * (to - from) + from
}
/// The size of the rectangle
let a = 10.0
/// The radius of the inner circle
let r = a / 2
///
let loopCount = 100000000
var circleCount = 0
let rangeLower = -5.0
let rangeUpper = 5.0
for _ in 0..<loopCount {
let x = rand(from: rangeLower, to: rangeUpper)
let y = rand(from: rangeLower, to: rangeUpper)
if x * x + y * y <= r * r {
circleCount += 1
}
}
let rate = Double(circleCount) / Double(loopCount)
let pi = (rate * a * a) / (r * r)
print(pi)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment