Last active
September 5, 2016 13:10
-
-
Save KelvinJin/44f5d87c8a438c97236c90cce972d31e to your computer and use it in GitHub Desktop.
Calculate 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
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