Transcription of Chapter 1 Iteration - MathWorks
1 Chapter 1 IterationIteration is a key element in much of technical computation. Examples involving theGolden Ratio introduce theMatlabassignment statement,forandwhileloops,and by picking a number, any number. Enter it intoMatlabby typingx =your numberThis is aMatlabassignment statement. The number you chose is stored in thevariablexfor later use. For example, if you start withx = 3 Matlabresponds withx =3 Next, enter this statementx = sqrt(1 + x)The abbreviationsqrtis theMatlabname for the square root function. Thequantity on the right, 1 +x, is computed and the result stored back in the variablex, overriding the previous value on your computer keyboard, probably in the lower right corner,you should be able to find four arrow keys. These are thecommand line up-arrow key allows you to recall earlier commands, including commands fromCopyrightc 2011 Cleve MolerMatlabR is a registered trademark of MathWorks , 2, 201112 Chapter 1. Iterationprevious sessions, and the other arrows keys allow you to revise these the up-arrow key, followed by the enter or return key, to iterate, or repeatedlyexecute, this statement:x = sqrt(1 + x)Here is what you get when you start withx = =3x =2x = = = = = = = = = = values are 3, 1 + 3, 1 + 1 + 3, 1 + 1 + 1 + 3, and so on.
2 After10 steps, the value printed remains constant Try several other startingvalues. Try it on a calculator if you have one. You should find that no matter whereyou start, you will always about ten steps. (Maybe a few more willbe required if you have a very large starting value.)Matlabis doing these computations to accuracy of about 16 decimal digits,but is displaying only five. You can see more digits by first enteringformat longand repeating the experiment. Here are the beginning and end of 30 steps startingatx= =33x =2x = = = = = about thirty or so steps, the value that is printed doesn t change any have computed one of the most famous numbers in mathematics, , theGolden , and most other programming languages, the equals sign is theassignment operator. It says compute the value on the right and store it in thevariable on the left. So, the statementx = sqrt(1 + x)takes the current value ofx, computessqrt(1 + x), and stores the result back mathematics, the equals sign has a different 1 +xis anequation.
3 A solution to such an equation is known as a xed point. (Be carefulnot to confuse the mathematical usage of xed pointwith the computer arithmeticusage of xed point.)The functionf(x) = 1 +xhas exactly one fixed point. The best way tofind the value of the fixed point is to avoid computers all together and solve theequation using the quadratic formula. Take a look at the hand calculation shownin figure The positive root of the quadratic equation is the Golden Ratio. =1 + can haveMatlabcompute directly using the statementphi = (1 + sqrt(5))/2 Withformat long, this produces the same value we obtained with the fixed pointiteration,phi = 1. IterationFigure the xed point by hand. 101234 1 xed point at = is our first example ofMatlabgraphics. It shows the intersectionof the graphs ofy=xandy= 1 +x. The statementx = -1:.02:4;generates a vectorxcontaining the numbers from -1 to 4 in steps of .02. Thestatementsy1 = x;y2 = sqrt(1+x);plot(x,y1,'-',x,y2,'-',phi,phi ,'o')5produce a figure that has three components.
4 The first two components are graphsofxand 1 +x. The'-'argument tells theplotfunction to draw solid lines. Thelast component in the plot is a single point with both coordinates equal to . The'o'tells theplotfunction to draw a has many variations, including specifying othercolors and line types. You can see some of the possibilities withhelp plot 111 Figure golden Golden Ratio shows up in many places in mathematics; we ll see severalin this book. The Golden Ratio gets its name from the golden rectangle, shown infigure The golden rectangle has the property that removing a square leaves asmaller rectangle with the same shape. Equating the aspect ratios of the rectanglesgives a defining equation for :1 = both sides of this equation by produces the same quadratic polynomialequation that we obtained from our fixed point Iteration . 2 1 = up-arrow key is a convenient way to repeatedly execute a single statement,or several statements, separated by commas or semicolons, on a single line.
5 Twomore powerful constructs are theforloop and thewhileloop. Aforloop executesa block of code a prescribed number of = 3for k = 1:31x = sqrt(1 + x)end6 Chapter 1. Iterationproduces 32 lines of output, one from the initial statement and one more each timethrough the executes a block of code an unknown number of times. Termi-nation is controlled by a logical expression, which evaluates totrueorfalse. Hereis the simplestwhileloop for our fixed point = 3while x ~= sqrt(1+x)x = sqrt(1+x)endThis produces the same 32 lines of output as theforloop. However, this code isopen to criticism for two reasons. The first possible criticism involves the termi-nation condition. The expressionx ~= sqrt(1+x)is theMatlabway of writingx = 1 +x. With exact arithmetic,xwould never be exactly equal tosqrt(1+x),the condition would always be true, and the loop would run forever. However, likemost technical computing environments,Matlabdoes not do arithmetic order to economize on both computer time and computer memory,Matlabuses oating pointarithmetic.
6 Eventually our program produces a value ofxfor whichthe floating point numbersxandsqrt(1+x)are exactly equal and the loop termi-nates. Expecting exact equality of two floating point numbers is a delicate works OK in this particular situation, but may not work with more second possible criticism of our simplewhileloop is that it is inefficient. Itevaluatessqrt(1+x)twice each time through the loop. Here is a more complicatedversion of thewhileloop that avoids both = 3y = 0;while abs(x-y) > eps(x)y = x;x = sqrt(1+x)endThe semicolons at the ends of the assignment statements involvingyindicate thatno printed output should result. The quantityeps(x), is the spacing of the floatingpoint numbers nearx. Mathematically, the Greek letter , orepsilon, often rep-resents a small quantity. This version of the loop requires only one square rootcalculation per Iteration , but that is overshadowed by the added complexity of thecode. Bothwhileloops require about the same execution time.
7 In this situation, Iprefer the firstwhileloop because it is easier to read and and DocMatlabhas extensive on-line documentation. Statements likehelp sqrthelp for7provide brief descriptions of commands and functions. Statements likedoc sqrtdoc forprovide more extensive documentation in a separate obscure, but very important,helpentry is about the various punctuationmarks and special characters used byMatlab. Take a look now athelp punctdoc punctYou will probably want to return to this information as you learn more are formed from the digits0through9, an optional decimal point, aleading+or-sign, an optionalefollowed by an integer for a power of 10 scaling,and an optionaliorjfor the imaginary part of a complex the value of . Here are some examples of +4ipiAssignment statements and namesA simple assignment statement consists of a name, an = sign, and a number. Thenames of variables, functions and commands are formed by a letter, followed by anynumber of upper and lower case letters, digits and underscores.
8 Single characternames, likexandN, and anglicized Greek letters, likepiandphi, are often usedto reflect underlying mathematical notation. Non-mathematical programs usuallyemploy long variable names. Underscores and a convention known as camel casingare used to create variable names out of several = 42phi = (1+sqrt(5))/2 Avogadros_constant = = -3+4iExpressionsPower is denoted by^and has precedence over all other arithmetic and division are denoted by*,/, and\and have precedence overaddition and subtraction, Addition and subtraction are denoted by+and-and8 Chapter 1. Iterationhave lowest precedence. Operations with equal precedence are evaluated left toright. Parentheses delineate subexpressions that are evaluated first. Blanks helpreadability, but have no effect on of the following expressions have the same value. If you don t alreadyrecognize this value, you can ask Google about its importance in popular *4 + 5*63 * 4+5 * 62*(3 + 4)*3-2^4 + 10*29/53\12652-8-2 Recap%% Iteration Chapter Recap% This is an executable program that illustrates the statements% introduced in the Iteration Chapter of "Experiments in MATLAB".
9 % You can run it by entering the command%% iteration_recap%% Better yet, enter%% edit iteration_recap%% and run the program cell-by-cell by simultaneously% pressing the Ctrl-Shift-Enter Enter%% publish iteration_recap%% to see a formatted Help and Documentation% help punct% doc punct%% Formatformat short100/81format long100/81format short9format compact%% Names and assignment statementsx = 42phi = (1+sqrt(5))/2 Avogadros_constant = = -3+4i%% Expressions3*4 + 5*63 * 4+5 * 62*(3 + 4)*3-2^4 + 10*29/53\12652-8-2%% Iteration % Use the up-arrow key to repeatedly executex = sqrt(1+x)x = sqrt(1+x)x = sqrt(1+x)x = sqrt(1+x)%% For loopx = 42for k = 1:12x = sqrt(1+x);disp(x)end%% While loopx = 42;k = 1;while abs(x-sqrt(1+x)) > 5e-5x = sqrt(1+x);k = k+1;endk%% Vector and colon operatork = 1:12x = ( : : )'%% Plotx = -pi: pi/256: pi;y = tan(sin(x)) - sin(tan(x));10 Chapter 1. Iterationz = 1 + tan(1);plot(x,y,'-', pi/2,z,'ro')xlabel('x')ylabel('y')title( 'tan(sin(x)) - sin(tan(x))')%% Golden Spiralgolden_spiral(4) evaluate each of these mathematical 34sin 14(32)( 3)4sin 1 (43)24 3 sin 34 32 2 4/3(arcsin 1)/ You can get started withhelp ^help conversion.
10 (a) Write aMatlabstatement that converts temperature in Fahrenheit,f, to Cel-sius, =something involvingf(b) Write aMatlabstatement that converts temperature in Celsius,c, to Fahren-heit, =something Abarnis a unit of area employed by high energy scattering experiments try to hit the side of a barn . Aparsecis a unitof length employed by astronomers. A star at a distance of one parsec exhibitsa trigonometric parallax of one arcsecond as the Earth orbits the Sun. Abarn-megaparsecis therefore a unit of volume a very long skinny barn is 10 28square megaparsec is parsec is light-year is cubic meter is milliliter one barn-megaparsec in teaspoons. InMatlab, the letterecan be usedto denote a power of 10 exponent, so 1015can be happens if you start with a large negative value ofxand repeatedly iteratex = sqrt(1 + x) is larger, or ? best way to solvex= 1 +xorx2= 1 +xis to avoid computers all together and just do it yourself by hand.