
4.6 The Finite Difference Method 261
loops. The first (outer) loop advances j from 0 to N
t
− 1, and within this loop there is
a second loop, which advances i from 1 to N
x
− 1. The entire algorithm is realized
in the R-program
HeatClos.r which is a part of the book software. The essential
part of this code consists of the two loops just mentioned:
1: for (j in 0:Nt){
2: for (i in 2:Nx)
3: T[i,2]=T[i,1]+eta*(T[i+1,1]+T[i-1,1]-2*T[i,1])
4: for (i in 2:Nx)
5: T[i,1]=T[i,2]
6:
...
7: }
(4.93)
The outer loop over j is defined in line 1 using Rs for command, which works
similar to Maximas
for command that was discussed in Section 3.8.1.2. This
commands iterates anything enclosed in brackets ‘‘
{...}’’ in lines 1–7, using
successive values
j = 0, j = 1, ...,j = Nt. The inner loop over i is in lines
2–3. The range of both the loops is slightly different from the ranges discussed
above for purely technical reasons (R does not allow arrays having index ‘‘0’’, and
hence all indices in
HeatClos.r begin with ‘‘1’’ instead of ‘‘0’’). The temperatures
are computed in line 3, which is in exact correspondence with Equation 4.86, except
for the fact that the index ‘‘2’’ is used here instead of ‘‘j + 1’’ and index ‘‘1’’ instead
of j. This means that
HeatClos.r stores the temperatures at two times only, the
‘‘new’’ temperatures in
T[i,2] and the ‘‘old’’ temperatures in T[i,1].Thisis
done to save memory since one usually wants to have the temperature at a few
times only as a result of the computation. In
HeatClos.r,avectorto defines these
fewpointsintimeandthe6ofthecode(whichwehaveleftouthereforbrevity).
After each time step, the next time step is prepared in lines 4–5 where the new
‘‘old’’ temperature is defined as the old ‘‘new’’ temperature.
Figure 4.6 shows the result of the computation. Obviously, there is a perfect
coincidence between the numerical solution (lines) and the closed form solution,
Equation 4.67. As was mentioned above, you can imagine Figure 4.6 to express
the temperature distributions within a one-dimensional physical body such as the
cylinder shown in Figure 4.1a. At time 0, the top curve in the figure shows a
sinusoidal temperature distribution within that body, with temperatures close to
100
◦
C in the middle of that body and temperatures around 0
◦
Catitsends.The
ends of the body are kept at a constant temperature of 0
◦
C according to Equations
4.69 and 4.70. Physically, you can imagine the ends of that body to be in contact
with ice water. In such a situation, physical intuition tells us that a continuous heat
flow will leave that body through its ends, accompanied by a continuous decrease
of the temperature within the body until T(x) = 0(x ∈ [0, 1]) is achieved. Exactly
this can be seen in the figure, and so you see that this solution of the heat equation
corresponds with our physical intuition. Note that the material parameters used
in this example (Figure 4.6 and
HeatClos.r) correspond to a body made up of
aluminum.