Programming in Mathematics

For this week's assignment, we are going to concentrate on loops and conditional statements. Videos to help with these concepts are You may also want to review the class notes.


Homework 2
  • Create an m-file called hw2Last.m where Last is the first four letters of your last name in your MA302 folder. A startup m-file is located here.

  • For the first problem, create a script cosLast.m that provides the first n non-zero term expansion of the Taylor's series for cos(x) around x=0. Hint: The first two non-description lines of cosLast.m should be
    cosx = ___;
    for i = 1:n-1

    Here n will be defined in hw2Last.m. Calculate the approximation for n=2,5,10 on the domain [0,4pi]. Plot each approximation along with the actual cos(x) for the x-axis being from 0 to 4pi and your y-axis being from -1 to 1. Be sure to distinguish between the lines. What does this plot tell you about approximating cos(x) using the Taylor's series about x=0 for points far away from 0?

  • For the second problem, we are interested in calculating an appropriate approximation of cos(4pi). One method is to compare the first n non-zero term expansion of the Taylor's series with the first n+1 term expansion. Continue looping through until the difference (in absolute value) is below some set tolerance. Here assume the tolerance is 1e-6. Plot the error per iteration. You may want to use the semilogy command for plotting.

  • For the third problem, we will be growing ferns by random repetition of a few simple matrix/vector transformations. For each step a random number is generated and dependent on the number one of four possible transformations occur. Your program should successively generate a random number and should

    • apply z = [0 0; 0 0.16] * z with probability 0.01
    • apply z = [0.85 0.04; -0.04 0.85] * z + [0; 1.6] with probability 0.85
    • apply z = [0.2 -0.26; 0.23 0.22] * z + [0; 1.6] with probability 0.07
    • apply z = [-0.15 0.28; 0.26 0.24] * z + [0; 0.44] with probability 0.07

    starting with z = [0; 0]. This recursion should occur n=10,000 times. You should accomplish this with a single if clause, although, given that your logic now forks four ways, you will want to make use of some subordinate elseif statements. Note: To make your code run faster there should be only 1 plot statement.

  • Post your m-file hw2Last.m to Dr. Shah's Dropbox account. In order to get full credit, your directories and files must be named correctly and you must have links to your function file and the m-file (script file) that created the webpage, along with the appropriate text, plots, and such to answer the problems.