TASK: Estimate your chances of forming a triangle after randomly breaking a unit stick into three pieces.
COMMENT: If X, Y and Z are the lengths of the sides of a triangle, then they must satisfy all three versions of the triangle inequality:
X <= Y + Z Y <= X + Z Z <= X + Y
We break the stick at two places, P1, and P2, whose values are determined by calling rand().
We now have to think about how P1 and P2 define the lengths of our pieces. We assume the stick is broken up into pieces of length X, Y and Z, in that order. The break between X and Y is either P1 or P2...we don't know which it is. But in fact, since this break occurs first, it must be whichever of P1 and P2 is smaller. And the second break, between Y and Z, occurs at the larger of P1 and P2.
<-X-> <-Y-> <-Z-> 0----------min(P1,P2)----------max(P1,P2)----------1
Using this idea, we can determine the values of X, Y and Z. Then we can determine whether X, Y and Z can form a triangle. To estimate the probability of a triangle, we will do the experiment N times. If we let M count the number of times our random values form a triangle, then we want to report the value M/N at the end.
INSTRUCTIONS:
Use the input() statement to get a value of n from the user. Initialze the variable "m" to zero. Start a for loop that repeats n times. Use rand() to set p1 and p2. Figure out how to determine x, y, and z from p1 and p2. if x, y, and z can form a triangle, increase m. end fprintf ( ' Using N=%d trials, estimated probability is %g\n', n, m / n );
CHECK: You want to use a large value of N to check your code, but as a guide, when I used N=20, I got an estimated probability of 0.2 which is not too far from the right answer.
SUBMIT: Your work should be stored in a script file called "hw025.m". Your script file should begin with at least three comment lines:
% hw025.m % YOUR NAME % This script (describe what it does) % Add any comments here that you care to make.If this problem is part of an assignment, then submit it to Canvas.