Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 39 ยท Projects and Practice

Project: 1D Heat Diffusion Simulation

Simulate heat flow along a rod in Fortran with an explicit finite-difference scheme: array slices, stability limit, boundary conditions, output files and plotting.

Physical simulation is what Fortran was built for. In this project you model a metal rod whose ends are held at fixed temperatures and watch heat spread along it. You will turn a differential equation into a few lines of array code, discover the stability limit of the method, write the results to a file and check them against the exact steady state.

The Fortran compiler is not available on this site, so the Fortran listing is read-only. The Python stand-in runs the same scheme so you can experiment with the parameters.

The physics

Temperature u(x, t) along a rod obeys the heat equation:

TEXT
du/dt = alpha * d2u/dx2

alpha is the thermal diffusivity. Heat flows from hot to cold, and the curvature of the temperature profile (the second derivative) drives how fast each point changes.

The numerical scheme (FTCS)

Split the rod into n points spaced dx apart and step time in increments of dt. Replace the derivatives with differences (forward in time, centered in space):

TEXT
u_new(i) = u(i) + r * (u(i-1) - 2*u(i) + u(i+1))      with   r = alpha * dt / dx**2

Each new temperature is the old one plus a correction pulling it toward the average of its neighbors. The scheme is explicit: every new value uses only old values, so one array expression computes the whole rod.

Stability: this scheme only works if r <= 0.5. Larger values make the numbers oscillate and blow up. This is a real limit, and you will provoke it below.

flowchart LR
    A["initial u(x)"] --> B["apply boundary values"]
    B --> C["u_new(2:n-1) = u + r * (left - 2u + right)"]
    C --> D["swap u, u_new"]
    D --> E{"enough steps?"}
    E -->|no| B
    E -->|yes| F["write result"]

One time step: set boundaries, compute the interior, swap.

The program

FORTRAN
program heat1d
  use, intrinsic :: iso_fortran_env, only: dp => real64
  implicit none

  integer, parameter :: n = 51            ! grid points
  integer, parameter :: nsteps = 20000
  real(dp), parameter :: length = 1.0_dp
  real(dp), parameter :: alpha = 1.0e-2_dp
  real(dp) :: dx, dt, r
  real(dp) :: u(n), unew(n)
  integer :: step, i, out

  dx = length / real(n - 1, dp)
  dt = 0.4_dp * dx**2 / alpha              ! r = 0.4: stable
  r  = alpha * dt / dx**2

  u = 0.0_dp                               ! rod starts cold
  u(1) = 100.0_dp                          ! left end held at 100
  u(n) = 0.0_dp                            ! right end held at 0
  unew = u

  do step = 1, nsteps
    unew(2:n-1) = u(2:n-1) + r * (u(1:n-2) - 2.0_dp * u(2:n-1) + u(3:n))
    unew(1) = 100.0_dp                     ! boundary conditions
    unew(n) = 0.0_dp
    u = unew
  end do

  open (newunit=out, file="heat.dat", status="replace", action="write")
  do i = 1, n
    write (out, "(f8.4, 1x, f10.5)") (i - 1) * dx, u(i)
  end do
  close (out)

  print "(a, f6.3)", "r = ", r
  print "(a, f8.3)", "temperature at the middle: ", u((n + 1) / 2)
end program heat1d

Study these lines:

  • unew(2:n-1) = ... computes every interior point at once from u(1:n-2), u(2:n-1) and u(3:n): three shifted views of the same array. No loop over i is written (do concurrent and elemental).
  • The right side is fully evaluated before the assignment, so using u on the right and unew on the left keeps the update clean.
  • Boundary values are re-imposed each step (Dirichlet conditions).
  • dt is chosen from r, not the other way around, so stability is guaranteed by construction.

What to expect

After a long time the temperature settles into the steady state, where d2u/dx2 = 0: a straight line from 100 at the left to 0 at the right. At the middle of the rod it is 50. With 20,000 steps the simulated time is nsteps * dt: here dt = 0.4 * (0.02)**2 / 0.01 = 0.016, giving 320 time units, many times the diffusion time L**2/alpha = 100, so the profile is essentially linear and the middle prints close to 50.

Python Stand-in: run the scheme and watch it converge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Break it on purpose

Change 0.4_dp to 0.6_dp, so r = 0.6. The middle temperature will not settle: small errors double each step, and after a few hundred steps the values are enormous and alternate in sign. This is an instability, not a bug in the code. The cure is to shrink dt, or switch to an implicit scheme (Crank-Nicolson, backward Euler) that stays stable at any dt, at the cost of solving a linear system each step, the topic of the next project.

Python Stand-in: instability when r is too large

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Visualizing the result

The file heat.dat has two columns, position and temperature. Plot it with any tool: gnuplot, Python with matplotlib (np.loadtxt("heat.dat")), or a spreadsheet. Save a snapshot every few hundred steps to a numbered file (use an internal write to build the file name, see formatted output) to see the profile evolve.

Extensions

  1. Add a heat source term + dt * q(i) for a heated section.
  2. Use an insulated end (zero gradient): unew(n) = unew(n-1).
  3. Extend to two dimensions with u(i, j), averaging four neighbors, and remember column-major order for the inner loop.
  4. Wrap the update in a module procedure and write a test that compares with the analytic solution at an intermediate time.
  5. Parallelize the step with !$omp parallel do (OpenMP in Fortran) for n = millions.
  6. Use real32 and compare accuracy with real64.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the stability condition of this explicit scheme?

    With r = alpha*dt/dx**2 above 0.5, errors grow each step and the solution blows up.
  2. 2. Why does the program compute into unew instead of overwriting u directly?

    The explicit formula uses only old values, so the update reads u and writes unew.
  3. 3. What temperature does the middle of the rod approach?

    The steady state is linear between 100 and 0, so the midpoint is 50.
  4. 4. What does halving dx do to the largest stable dt?

    r = alpha*dt/dx**2 is fixed at the limit, so dt scales with dx squared.

Summary

  • Discretize the heat equation into an array update with shifted slices.
  • Pick dt from the stability limit r <= 0.5.
  • Impose boundary conditions each step and swap or copy arrays.
  • Validate against the steady state and write results to a file.
  • Unstable runs teach why implicit methods exist.

Next: Project: a linear system solver