W1292 Useful Randomness

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder
Random Bitmap
Kuntze-Konicz Fortune

Prerequisites[edit]

Research[edit]


Introduction[edit]

In swift it is possible to return random numbers within a range as a method. Using the .random method will allow you to choose a number within a range. The for loop below demonstrates a range of numbers and random numbers printed each time the loop runs.

for _ in 1...5 {
    print(Int.random(in: 1..<50))
}
// Prints "49"
// Prints "32"
// Prints "15"
// Prints "9"
 <syntaxhighlight>


== Background ==
{{ComingSoon|
Add section on throwing dart at ¼ of square
}}


[[File:Unit circle 3.svg|300px|Unit circle 3]]</br>

The value of π can be calculated by:
# Randomly throwing "darts" at a unit circle 
# Counting the total number of "darts", ''N''
# Counting the number of "darts" that fall within the unit circle, ''C''
# The ratio of the area inside the circle to the total area is C/N
# The value of π is four times this value (because the area of the total square is 2 units x 2 units)

== Prepare ==
Create a new directory in your ~/Experiences directory named "W1292".
Use emacs to edit a file named "main.swift":
{{ConsoleLine|zay-vin@codermerlin:~$ |cd ~/Experiences}}
{{ConsoleLine|zay-vin@codermerlin:~/Experiences$ |mkdir W1292}}
{{ConsoleLine|zay-vin@codermerlin:~/Experiences$ |cd W1292}}
{{ConsoleLine|zay-vin@codermerlin:~/Experiences/project-1292$ |swift-init}}
{{ConsoleLine|zay-vin@codermerlin:~/Experiences/project-1292$ |emacs main.swift}}


{{Hint|
You can run your program from within emacs with {{Key|F5}}-{{Key|r}}
}}


{{Hint|
You can find the square root of a number using the {{SwiftIdentifier|squareRoot}} function.  This function is included in the {{SwiftLibrary|Foundation}} library, so it must be imported.

For example:
<syntaxhighlight lang="swift" highlight="1,4">
import Foundation

let d = 12.0
print(d.squareRoot())

}}


ObserveObserveIcon.png
Observe, Ponder, and Journal: Section 1

Complete your program, then answers these questions.

  1. Estimate the value of π using your program
    1. Throw 100 darts (N = 100). What result do you obtain?
    2. Throw 1000 darts (N = 1000). What result do you obtain?
  2. How is the second result different from your previous result?
  3. How large should N be to accurately estimate π to five digits?
  4. How important is it that the dart be "thrown" randomly?

Exercises[edit]

Template:W1292-Exercises

Key Concepts[edit]

Key ConceptsKeyConceptsIcon.png
  • Random numbers meet the following two criteria:
    • Even distribution over a defined interval
    • Impossible to predict subsequent values based upon previous values
  • Random numbers can be very useful in certain circumstances