Name: Tiffany Jiang
Date: 14-Mar-2023
I received assistance from: NO ONE
I assisted: NO ONE
1) Throwing 100 darts, my result is 3.24. 2) Throwing 1000 darts, the result obtained is 3.108. (Throwing 1 million darts, I obtain 3.143676)
The second result is more precise, and has more significant figures.
At least 1,000,000,000, assuming the margin of error would be four digits.
It makes sure that the spread of the darts across the board would generally be even and unbiased.
1 #!/usr/bin/swift
2 import Foundation
3
4 //Get coordinates (is in first quadrant.)
5 func coordinates() -> [Double] {
6 let x = Double.random(in: 0...1)
7 let y = Double.random(in: 0...1)
8 return [x,y]
9 }
10
11 //Test if coordinates are in a circle of radius of 1
12 func isInCircle(x: Double, y: Double) -> Bool {
13 // Use pythagorean theorem to find the length of the "hypotenuse" between the origin and the given coordinates.
14 let pythag = sqrt((x*x) + (y*y))
15 // If the hypotenuse's lenght is greater than 1, then the point is outside of the circle.
16 if pythag <= 1 {
17 return true
18 } else {
19 return false
20 }
21 }
22
23 func main() {
24 // Declare variables for amount of darts within the circle, and total darts to throw.
25 var count = 0
26 let totalDarts = 10000000
27
28 for _ in 0...totalDarts {
29 // Throw the darts.
30 let coords: [Double] = coordinates()
31 // Add to the count for amount of darts within the circle if the dart lands within the 'circle.'
32 if isInCircle(x: coords[0], y: coords[1]) {
33 count += 1
34 }
35 }
36
37 // Divide the amount of darts within the circle by the total amount of darts thrown and multiply by four becaus\
e only the first quadrant was considered.
38 print((Double(count)/Double(totalDarts))*4)
39 }
40
41 // Run the function.
42 main()
I learned more about the utilization of Swift's .random function and the origins of Pi.
Realizing the logic was simple, but organizing them into different functions was not, as this messed with the overall simple and linear flow of instruction. Organizing the variables to not be global was also a perplexing endeavor.
Clarification in the instructions about finding Pi can be made. The 5th instruction assumes that the student uses the range "0...1" when randomizing numbers, but one can also use the full range of "-1...1", thus making this fifth instruction to be confusing as the ratio (mentioned in the 4th instruction) is already the full correct one.
After completing the exercise, I have a better understanding of swift coding, using Foundation, and Pi, and randomness.