Swift版 通過概率計算圓周率
阿新 • • 發佈:2020-12-13
程式碼:
class Pi{
public static func caculate() -> Double{
let n = 1000000
var k = 0
for _ in 1..<n {
let x: Double = Double(arc4random_uniform(10000))
let y: Double = Double(arc4random_uniform(10000))
if (x*x + y*y) <= 1 {
k = k + 1
}
}
let result: Double = Double((4 * k)) / Double(n)
return result
}
}
print("Pi is: " + String(Pi.caculate()))
說明:這裡的n為模擬投擲的次數,這裡為1000000。讀者可調控n的值來提高精度。