2.6.7 Evaluation in Iteration FunctionsThe built-in Mathematica iteration functions such as Table and Sum, as well as Plot and Plot3D, evaluate their arguments in a slightly special way. When evaluating an expression like Table[f, {i, imax}], the first step, as discussed in Section 2.7.6, is to make the value of i local. Next, the limit imax in the iterator specification is evaluated. The expression f is maintained in an unevaluated form, but is repeatedly evaluated as a succession of values are assigned to i. When this is finished, the global value of i is restored. | The function Random[ ] is evaluated four separate times here, so four different pseudorandom numbers are generated. | |
In[1]:=
Table[Random[ ], {4}]
|
Out[1]=
|
|
| This evaluates Random[ ] before feeding it to Table. The result is a list of four identical numbers. | |
In[2]:=
Table[ Evaluate[Random[ ]], {4} ]
|
Out[2]=
|
|
In most cases, it is convenient for the function f in an expression like Table[f, {i, imax}] to be maintained in an unevaluated form until specific values have been assigned to i. This is true in particular if a complete symbolic form for f valid for any i cannot be found. | This defines fac to give the factorial when it has an integer argument, and to give NaN (standing for "Not a Number") otherwise. | |
In[3]:=
fac[n_Integer] := n! ; fac[x_] := NaN
|
|
| In this form, fac[i] is not evaluated until an explicit integer value has been assigned to i. | |
In[4]:=
Table[fac[i], {i, 5}]
|
Out[4]=
|
|
| Using Evaluate forces fac[i] to be evaluated with i left as a symbolic object. | |
In[5]:=
Table[Evaluate[fac[i]], {i, 5}]
|
Out[5]=
|
|
In cases where a complete symbolic form for f with arbitrary i in expressions such as Table[f, {i, imax}] can be found, it is often more efficient to compute this form first, and then feed it to Table. You can do this using Table[Evaluate[f], {i, imax}]. | The Sum in this case is evaluated separately for each value of i. | |
In[6]:=
Table[Sum[i^k, {k, 4}], {i, 8}]
|
Out[6]=
|
|
| It is however possible to get a symbolic formula for the sum, valid for any value of i. | |
Out[7]=
|
|
| By inserting Evaluate, you tell Mathematica first to evaluate the sum symbolically, then to iterate over i. | |
In[8]:=
Table[Evaluate[Sum[i^k, {k, 4}]], {i, 8}]
|
Out[8]=
|
|
| Table[f, {i, imax}] | keep f unevaluated until specific values are assigned to i | | Table[Evaluate[f], {i, imax}] | evaluate f first with i left symbolic |
Evaluation in iteration functions. As discussed in Section 1.9.1, it is convenient to use Evaluate when you plot a graph of a function or a list of functions. This causes the symbolic form of the function or list to be found first, before the iteration begins.
|