Skip to main content

more options

Self-check exercise: While-loops

  1. The value of (π^2)/8 can be approximated by the series
    sum of reciprocals of odd numbers
    Write a script that evaluates this expression, ignoring all terms that are strictly smaller than .000001. Your script should display the number of terms summed and the sum. Use a while-loop. Think about the initialization of your variables and the order of computation carefully! In the loop body you need to calculate the value of a term only once.
  2. We use the above series for approximating (π^2)/8 again but with a different stopping criterion. Let the sum of the first n terms be Tn. As n increases one expects the ratio Tn/Tn+1 to approach 1. Write a script to find the smallest n such that the ratio this ratio is greater than 0.9999. Display n and Tn.
    Hint: Now you need to keep track of a current sum and the next sum in the loop.
  3. Complete the script stepPyramidSkeleton.m to draw a step pyramid, as the one shown below.

    a step pyramid

    The base rectangle is L-by-H where H < L. Each step has the same height H. The next rectangle up is 2/3 the length of the rectangle below, and so forth. The top step must have a length no less than H.
    Note: To draw a single rectangle, you can make use of the function DrawRect that we have defined for you in file DrawRect.m . To use this function, save this file to your MATLAB working directory and call it from your script with the syntax DrawRect(a,b,L,H,c) to draw a rectangle with lower-left corner at (a,b) a (horizontal) length L, a height H and color c which should be one of 'r', 'g', 'y'.
  4. How many rolls of a fair die does one need to accumulate at least 20 points? Of course one needs at least 4 rolls (as in 6 + 6 + 6 + 2 or 6 + 5 + 4 + 5) and at most 20 rolls (getting 20 1's in a row). However these sittuations are rather unlikely! Hence, we ask ourselves: what is the most likely number of times that one has to roll a die to get 20 points? Write a program to answer this question.
    • First write a fragment of code that simulates one experiment run, i.e. rolling the die several times until 20 points have been accumulated and counting how many times the die was rolled. Store this count in variable n
    • Test it.
    • Then insert this fragment in a loop to do many runs (say 10000). Do not forget to reset n to 0 at the beginning of the loop
    • Use an array counts to summarize the results, as follows. Start with counts being a vector of zeros of length 20. After each run increment component counts(n) by one if the run took n rolls of the die.
    • After running your program, sum(counts) should equal 10000 (the total number of runs) and [maxcount, maxn] = max(counts) will yield the maximum count and the value of n for which this count is obtained. maxn will be the most likely number of rolls of the die to get 20 points.