(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.
[1] 0.002582699 0.394225758 0.618501814 0.476891136 0.136097186 0.067384386
[7] 0.129152617 0.393117930
[1] 0.6469028 0.6202060 0.7644140 0.7438358 0.8261657 0.4227291 0.4092877
[8] 0.5396926
This function does the job, straight from the original breaks:
x | y | side1 | side2 | side3 | triangle |
---|---|---|---|---|---|
0.647 | 0.003 | 0.003 | 0.644 | 0.353 | FALSE |
0.394 | 0.620 | 0.394 | 0.226 | 0.380 | TRUE |
0.619 | 0.764 | 0.619 | 0.146 | 0.236 | FALSE |
0.477 | 0.744 | 0.477 | 0.267 | 0.256 | TRUE |
0.136 | 0.826 | 0.136 | 0.690 | 0.174 | FALSE |
0.067 | 0.423 | 0.067 | 0.355 | 0.577 | FALSE |
0.129 | 0.409 | 0.129 | 0.280 | 0.591 | FALSE |
0.393 | 0.540 | 0.393 | 0.147 | 0.460 | TRUE |
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 <- 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 = ""
)
}
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.