Skip to content

Added Monte Carlo in Swift 4.1 #197

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions chapters/monte_carlo/code/swift/monte_carlo.swift
Original file line number Diff line number Diff line change
@@ -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()

5 changes: 5 additions & 0 deletions chapters/monte_carlo/monte_carlo.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 %}


Expand Down