Skip to content

Commit eeb83e6

Browse files
Wesley-Arringtonjune128
authored andcommitted
Updating to Swift 4.2 (#386)
1 parent 5153e3b commit eeb83e6

File tree

2 files changed

+8
-24
lines changed

2 files changed

+8
-24
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,4 @@
1-
//Double Extension from YannickSteph on StackOverflow: https://stackoverflow.com/questions/25050309/swift-random-float-between-0-and-1
2-
3-
import Foundation
4-
5-
public extension Double {
6-
public static var random: Double {
7-
return Double(arc4random()) / 0xFFFFFFFF // Returns a random double between 0.0 and 1.0, inclusive.
8-
}
9-
10-
public static func random(min: Double, max: Double) -> Double {
11-
return Double.random * (max - min) + min
12-
}
13-
}
14-
15-
func isInCircle(x: Double, y: Double, radius: Double) -> Bool {
1+
func inCircle(x: Double, y: Double, radius: Double) -> Bool {
162
return (x*x) + (y*y) < radius*radius
173
}
184

@@ -21,16 +7,16 @@ func monteCarlo(n: Int) -> Double {
217
var piCount = 0
228
var randX: Double
239
var randY: Double
24-
10+
2511
for _ in 0...n {
26-
randX = Double.random(min: 0, max: radius)
27-
randY = Double.random(min: 0, max: radius)
28-
29-
if(isInCircle(x: randX, y: randY, radius: radius)) {
12+
randX = Double.random(in: 0..<radius)
13+
randY = Double.random(in: 0..<radius)
14+
15+
if(inCircle(x: randX, y: randY, radius: radius)) {
3016
piCount += 1
3117
}
3218
}
33-
19+
3420
let piEstimate = Double(4 * piCount)/(Double(n))
3521
return piEstimate
3622
}
@@ -41,6 +27,4 @@ func main() {
4127
print("Percent error is: \(100 * abs(piEstimate - Double.pi)/Double.pi)%")
4228
}
4329

44-
4530
main()
46-

Diff for: contents/monte_carlo_integration/monte_carlo_integration.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ each point is tested to see whether it's in the circle or not:
6060
{% sample lang="java" %}
6161
[import:13-15, lang:"java"](code/java/MonteCarlo.java)
6262
{% sample lang="swift" %}
63-
[import:15-17, lang:"swift"](code/swift/monte_carlo.swift)
63+
[import:1-3, lang:"swift"](code/swift/monte_carlo.swift)
6464
{% sample lang="py" %}
6565
[import:5-7, lang:"python"](code/python/monte_carlo.py)
6666
{% sample lang="cs" %}

0 commit comments

Comments
 (0)