(Section 6.4)
Recall the function for deciding if three side-lengths can make a triangle:
Recall that it worked on many triangles at once.
Probability Question:
What is the probability that the three pieces will form a triangle?
runif() and isTriangle() do vectorization, so they can handle repetition. Let’s repeat the random process eight times.
.. it is hard to interpret the results.
So let’s arrange them in a data frame:
This function does the job, straight from the original breaks:
How many times we got a triangle:
The proportion of times we got a triangle:
triangleSim_table <- function(reps = 10000, table = FALSE ) {
cut1 <- runif(reps)
cut2 <- runif(reps)
triangle <- makesTriangle(cut1, cut2)
if ( table ) {
cat("Here is a table of the results:\n")
print(table(triangle))
cat("\n")
}
cat("The proportion of triangles was ", mean(triangle), ".\n", sep = "")
}When you do “random stuff”, the results are liable to be different each time.
Run this command several times:
What if you want to keep a record of your results?
Try setting the seed for R’s random-number generator:
Run this several times. It’s always the same color!
You can start with a different seed:
Run this several times. It’s always the same color (but different from last time)!
triangleSim_table_seed <- function(reps = 10000, table = FALSE, seed = NULL) {
if ( !is.null(seed) ) {
set.seed(seed)
}
cut1 <- runif(reps)
cut2 <- runif(reps)
triangle <- makesTriangle(cut1, cut2)
if ( table ) {
cat("Here is a table of the results:\n\n")
print(table(triangle))
cat("\n")
}
cat(
"The chance of being able to form a triangle\n",
"is approximately ", mean(triangle), ".\n", sep = ""
)
}Try setting a seed:
Try not setting a seed:
Encapsulation and Generalization
A method for developing a computer program according to which the programmer first designs a basic procedure, then encapsulates it in one or more functions, and then progressively generalizes these functions until the program possesses all desired features.