diff --git a/chapters/monte_carlo/code/swift/monte_carlo.swift b/chapters/monte_carlo/code/swift/monte_carlo.swift new file mode 100644 index 000000000..29c21f953 --- /dev/null +++ b/chapters/monte_carlo/code/swift/monte_carlo.swift @@ -0,0 +1,57 @@ +//Double Extension from YannickSteph on StackOverflow: https://stackoverflow.com/questions/25050309/swift-random-float-between-0-and-1 + +import Foundation + + + +public extension Double { + + public static var random: Double { + + return Double(arc4random()) / 0xFFFFFFFF // Returns a random double between 0.0 and 1.0, inclusive. + } + + public static func random(min: Double, max: Double) -> Double { + + return Double.random * (max - min) + min + } +} + + +func isInCircle(x: Double, y: Double, radius: Double) -> Bool { + + return (x*x) + (y*y) < radius*radius +} + + +func monteCarlo(n: Int) -> Double { + + let radius: Double = 1 + var piCount = 0 + var randX: Double + var randY: Double + + for _ in 0...n { + randX = Double.random(min: 0, max: radius) + randY = Double.random(min: 0, max: radius) + + if(isInCircle(x: randX, y: randY, radius: radius)) { + piCount += 1 + } + } + + let piEstimate = Double(4 * piCount)/(Double(n)) + + return piEstimate +} + + +func main() { + let piEstimate = monteCarlo(n: 10000) + print("Pi estimate is: ", piEstimate) + print("Percent error is: \(100*(Double.pi - piEstimate)/Double.pi)%") +} + + +main() + diff --git a/chapters/monte_carlo/monte_carlo.md b/chapters/monte_carlo/monte_carlo.md index 2eb2d2e4d..3a04fbdbe 100644 --- a/chapters/monte_carlo/monte_carlo.md +++ b/chapters/monte_carlo/monte_carlo.md @@ -55,6 +55,8 @@ each point is tested to see whether it's in the circle or not: [import:12-14, lang:"golang"](code/go/monteCarlo.go) {% sample lang="java" %} [import:11-13, lang:"java"](code/java/MonteCarlo.java) +{% sample lang="swift" %} +[import:21-25, lang:"swift"](code/swift/monte_carlo.swift) {% endmethod %} If it's in the circle, we increase an internal count by one, and in the end, @@ -113,6 +115,9 @@ Feel free to submit your version via pull request, and thanks for reading! {% sample lang="java" %} ### Java [import, lang:"java"](code/java/MonteCarlo.java) +{% sample lang="swift" %} +### Swift +[import, lang:"swift"](code/java/monte_carlo.swift) {% endmethod %}