13.07.2015 Views

2.5.9 Loops and Control Structures - Wolfram Research

2.5.9 Loops and Control Structures - Wolfram Research

2.5.9 Loops and Control Structures - Wolfram Research

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

340 2. Principles of Mathematica<strong>2.5.9</strong> <strong>Loops</strong> <strong>and</strong> <strong>Control</strong> <strong>Structures</strong>The execution of a Mathematica program involves the evaluation of a sequence of Mathematica expressions.In simple programs, the expressions to be evaluated may be separated by semicolons, <strong>and</strong> evaluatedone after another. Often, however, you need to evaluate expressions several times, in some kindof “loop”.Do[expr, {i, imax}]Do[expr, {i, imin, imax, di}]Do[expr, {n}]evaluate expr repetitively, with i varying from 1 to imax insteps of 1evaluate expr with i varying from imin to imax in steps of dievaluate expr n timesSimple looping constructs.This evaluates Print[i^2], withirunning from 1 to 4.This executes an assignment for t in aloop with k running from 2 to 6 in stepsof 2.In[1]:= Do[Print[i^2], {i, 4}]14916In[2]:= t = x Do[t = 1/(1 + k t), {k, 2, 6, 2}] t1Out[2]= -----------------------------61 + ---------------------41 + -------------1 + 2 xThe way iteration is specified in Do is exactly the same as in functions like Table <strong>and</strong> Sum. Justasinthose functions, you can set up several nested loops by giving a sequence of iteration specifications toDo.This loops over values of i from 1 to 4,<strong>and</strong> for each value of i, loops over jfrom 1 to i-1.In[3]:= Do[Print[{i,j}], {i, 4}, {j, i-1}]{2, 1}{3, 1}{3, 2}{4, 1}{4, 2}{4, 3}Sometimes you may want to repeat a particular operation a certain number of times, without changingthe value of an iteration variable. You can specify this kind of repetition in Do just as you can inTable <strong>and</strong> other iteration functions.Web sample page from The Mathematica Book, Second Edition, by Stephen <strong>Wolfram</strong>, published by Addison-Wesley Publishing Company (hardcoverISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact <strong>Wolfram</strong> <strong>Research</strong>: info@wolfram.com;http://www.wolfram.com/; 1-800-441-6284.© 1991 <strong>Wolfram</strong> <strong>Research</strong>, Inc. Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction,or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.


2.5 Evaluation of Expressions 341This repeats the assignmentt=1/(1+t) three times.In[4]:= t = x Do[t = 1/(1+t), {3}] t1Out[4]= -------------------------11 + -----------------11 + ---------1 + xYou can put a procedure inside Do. In[5]:= t = 67 Do[Print[t] t = Floor[t/2], {3}]673316Nest[f, expr, n]FixedPoint[f, expr]apply f to expr n timesstart with expr, <strong>and</strong> apply f repeatedly until the result nolonger changesFixedPoint[f, expr, SameTest -> comp]stop when the function comp applied to two successiveresults yields TrueApplying functions repetitively.Do allows you to repeat operations by evaluating a particular expression many times with differentvalues for iteration variables. Often, however, you can make more elegant <strong>and</strong> efficient programs usingthe functional programming constructs discussed in Section 2.2.2. Nest[f, x, n], for example, allowsyou to apply a function repeatedly to an expression.This nests f three times. In[6]:= Nest[f, x, 3]Out[6]= f[f[f[x]]]By nesting a pure function, you can getthe same result as in the example withDo above.In[7]:= Nest[ Function[t, 1/(1+t)], x,3]1Out[7]= -------------------------11 + -----------------11 + ---------1 + xNest allows you to apply a function a specified number of times. Sometimes, however, you maysimply want to go on applying a function until the results you get no longer change. You can do thisusing FixedPoint[f, x].Web sample page from The Mathematica Book, Second Edition, by Stephen <strong>Wolfram</strong>, published by Addison-Wesley Publishing Company (hardcoverISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact <strong>Wolfram</strong> <strong>Research</strong>: info@wolfram.com;http://www.wolfram.com/; 1-800-441-6284.© 1991 <strong>Wolfram</strong> <strong>Research</strong>, Inc. Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction,or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.


342 2. Principles of MathematicaFixedPoint goes on applying a functionuntil the result no longer changes.In[8]:= FixedPoint[Function[t, Print[t] Floor[t/2]], 67]67331684210Out[8]= 0You can use FixedPoint to imitate the evaluation process in Mathematica, ortheoperationoffunctionssuch as expr //. rules. In general, FixedPoint goes on until two successive results it gets arethe same. By default, FixedPoint uses SameQ to test whether results are the same. You can specify analternative function to use by setting the SameTest option.While[test, body]For[start, test, incr, body]evaluate body repetitively, so long as test is Trueevaluate start, then repetitively evaluate body <strong>and</strong> incr, untiltest failsGeneral loop constructs.Functions like Do, Nest <strong>and</strong> FixedPoint provide rather structured ways to make loops in Mathematicaprograms. Sometimes, however, you need to create loops with less structure. In such cases, youmay find it convenient to use the functions While <strong>and</strong> For, which perform operations repeatedly, stoppingwhen a specified condition fails to be true.The While loop continues until thecondition fails.In[9]:= n = 17 While[(n = Floor[n/2]) != 0, Print[n]]8421The functions While <strong>and</strong> For in Mathematica are similar to the control structures while <strong>and</strong> for inlanguages such as C. Notice, however, that there are a number of important differences. For example,the roles of comma <strong>and</strong> semicolon are reversed in Mathematica For loops relative to C language ones.This is a very common form for a Forloop. i++ increments the value of i.Here is a more complicated For loop.Notice that the loop terminates as soonas the test i^2


2.5 Evaluation of Expressions 343In Mathematica, bothWhile <strong>and</strong> For always evaluate the loop test before evaluating the body of theloop. As soon as the loop test fails to be True, While <strong>and</strong> For terminate. The body of the loop is thusonly evaluated in situations where the loop test is True.The loop test fails immediately, so thebody of the loop is never evaluated.In[12]:= While[False, Print[x]]In a While or For loop, or in general in any Mathematica procedure, the Mathematica expressions yougive are evaluated in a definite sequence. You can think of this sequence as defining the “flow of control”in the execution of a Mathematica program.In most cases, you should try to keep the flow of control in your Mathematica programs as simple aspossible. The more the flow of control depends for example on specific values generated during theexecution of the program, the more difficult you will typically find it to underst<strong>and</strong> the structure <strong>and</strong>operation of the program.Functional programming constructs typically involve very simple flow of control. While <strong>and</strong> Forloops are always more complicated, since they are set up to make the flow of control depend on thevalues of the expressions given as tests. Nevertheless, even in such loops, the flow of control does notusually depend on the values of expressions given in the body of the loop.In some cases, however, you may need to construct Mathematica programs in which the flow of controlis affected by values generated during the execution of a procedure or of the body of a loop. Mathematicaprovides various functions for modifying the flow of control. The functions work somewhat asthey do in languages such as C.Break[ ]Continue[ ]Return[expr]Goto[name]Throw[expr]exit the nearest enclosing loopgo to the next step in the current loopreturn the value expr, exiting all procedures <strong>and</strong> loops in afunctiongo to the element Label[name] in the current procedurereturn expr as the value of the nearest enclosing Catch(non-local return)<strong>Control</strong> flow functions.The Break[ ]causes the loop toterminate as soon as t exceeds 19.In[13]:= t = 1 Do[t *= k Print[t]12624If[t > 19, Break[]], {k, 10}]Web sample page from The Mathematica Book, Second Edition, by Stephen <strong>Wolfram</strong>, published by Addison-Wesley Publishing Company (hardcoverISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact <strong>Wolfram</strong> <strong>Research</strong>: info@wolfram.com;http://www.wolfram.com/; 1-800-441-6284.© 1991 <strong>Wolfram</strong> <strong>Research</strong>, Inc. Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction,or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.


344 2. Principles of MathematicaWhen k 5, Return[big]] t = x^3 Return[t - 7])In[16]:= f[10]Out[16]= bigReturn[expr] allows you to exit a particular function, returning a value. Mathematica also providesa capability for non-local returns with which you can exit a sequence of nested functions. Non-localreturns can be convenient for h<strong>and</strong>ling certain error conditions.This function “throws” overflow if itsargument is greater than 10.g[20] throws overflow, whichisreturned as the value of the enclosingCatch.In[17]:= g[x_] := If[x > 10, Throw[overflow], x!]In[18]:= Catch[ 2 + g[20] ]Out[18]= overflowWeb sample page from The Mathematica Book, Second Edition, by Stephen <strong>Wolfram</strong>, published by Addison-Wesley Publishing Company (hardcoverISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact <strong>Wolfram</strong> <strong>Research</strong>: info@wolfram.com;http://www.wolfram.com/; 1-800-441-6284.© 1991 <strong>Wolfram</strong> <strong>Research</strong>, Inc. Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction,or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.


2.5 Evaluation of Expressions 345In this case, overflow is not generated,<strong>and</strong> the Catch has no effect.In[19]:= Catch[ 2 + g[5] ]Out[19]= 122Functions like Continue[ ] <strong>and</strong> Break[ ] allow you to “transfer control” to the beginning or endof a loop in a Mathematica program. Sometimes you may instead need to transfer control to a particularelement in a Mathematica procedure. If you give a Label as an element in a procedure, you can useGoto to transfer control to this element.This goes on looping until q exceeds 6.In[20]:= (q = 2 Label[begin] Print[q] q += 325If[q < 6, Goto[begin]])Note that you can use Goto in a particular Mathematica procedure only when the Label it specifiesoccurs as an element of the same Mathematica procedure. In general, use of Goto reduces the degree ofstructure that can readily be perceived in a program, <strong>and</strong> therefore makes the operation of the programmore difficult to underst<strong>and</strong>.Web sample page from The Mathematica Book, Second Edition, by Stephen <strong>Wolfram</strong>, published by Addison-Wesley Publishing Company (hardcoverISBN 0-201-51502-4; softcover ISBN 0-201-51507-5). To order Mathematica or this book contact <strong>Wolfram</strong> <strong>Research</strong>: info@wolfram.com;http://www.wolfram.com/; 1-800-441-6284.© 1991 <strong>Wolfram</strong> <strong>Research</strong>, Inc. Permission is hereby granted for web users to make one paper copy of this page for their personal use. Further reproduction,or any copying of machine-readable files (including this one) to any server computer, is strictly prohibited.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!