Last active
March 13, 2017 20:27
-
-
Save tikipatel/4bf4df2801de1a1da9e8ba8228fda93d to your computer and use it in GitHub Desktop.
Get an approximation of π using probabilities of coprime integers
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 | |
let rolls = 1_000_000 | |
func getPi() -> Double { | |
func gcd(x: Int, y: Int) -> Int { | |
var internal_x = x | |
var internal_y = y | |
while internal_y != 0 { | |
(internal_x, internal_y) = (internal_y, internal_x % internal_y) | |
} | |
return internal_x | |
} | |
var coprimesCount = 0 | |
for _ in 0..<rolls { | |
let a = arc4random() | |
let b = arc4random() | |
if gcd(x: Int(a), y: Int(b)) == 1 { | |
coprimesCount += 1 | |
} | |
} | |
let probability = Double(coprimesCount) / Double(rolls) | |
let pi = sqrt(6.0/probability) | |
print("approximatie π = \(pi)") | |
print("error: \(abs(pi-M_PI) / M_PI * 100)%") | |
return pi | |
} | |
for _ in 1...1000 { | |
getPi() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment