LAST SEEN ONLINE:
NOV 22, 2026 11:36 UTC
LOCAL_TIME_SYNC:
--:--:-- | -- _
← Digital notebook
CFD 29 min read First-Principles CFD / Module 12

Module 12: Implementing Convection and Diffusion Operators in C++

Derive and implement finite-volume convection and diffusion operators in C++, compare central and upwind schemes, assemble a linear system, and verify the numerical solution.

1. Introduction

In Module 11, we developed the architecture of a finite-volume CFD framework. We introduced meshes, scalar fields, boundary conditions, face-based fluxes, equation assembly, and linear-system interfaces.

The next step is to implement two of the most important spatial operators in computational fluid dynamics:

  • Diffusion, which transports a quantity down its gradient.
  • Convection, which transports a quantity with the moving fluid.

Together, these operators appear in equations for temperature, species concentration, momentum, turbulence quantities, and many other transported fields.

For example, the steady convection–diffusion equation for a scalar field ϕ\phi is

∇⋅(ρuϕ)=∇⋅(Γ∇ϕ)+Sϕ\nabla \cdot (\rho \mathbf{u}\phi) = \nabla \cdot (\Gamma \nabla \phi) + S_\phi

where:

  • ϕ\phi is the transported scalar.
  • ρ\rho is the fluid density.
  • u\mathbf{u} is the velocity vector.
  • Γ\Gamma is the diffusion coefficient.
  • SϕS_\phi is a volumetric source term.

The objective of this module is to transform this equation into a working C++ solver while understanding every numerical step.

By the end, you should be able to:

  1. Derive a finite-volume convection–diffusion equation.
  2. Calculate convective and diffusive face fluxes.
  3. Implement central-difference and upwind interpolation.
  4. Assemble a tridiagonal linear system.
  5. Solve the system using the Thomas algorithm.
  6. Compare numerical solutions with an analytical benchmark.
  7. Identify numerical diffusion, boundedness problems, and implementation errors.

2. Physical interpretation of convection and diffusion

2.1 Convection

Convection transports a quantity because the fluid itself is moving.

Imagine a warm fluid entering a cold channel. The fluid carries its thermal energy downstream. The transport rate depends on the fluid velocity, density, and transported quantity.

For a one-dimensional flow through a cross-sectional area AA, the convective flux of a scalar is

Jc=ρuAϕJ_c = \rho u A \phi

where uu is the velocity in the streamwise direction.

For a temperature field, the corresponding convective energy transport also involves the fluid’s heat capacity. The equation above is the general scalar-transport form, with the appropriate definition of ϕ\phi and its coefficients.

If the velocity is zero, there is no convective transport through the stationary fluid.

2.2 Diffusion

Diffusion transports a quantity because of spatial gradients.

For heat conduction, Fourier’s law states

q=−k∇T\mathbf{q} = -k \nabla T

where kk is the thermal conductivity and TT is temperature.

For a general scalar, the diffusive flux density is

jd=−Γ∇ϕ\mathbf{j}_d = -\Gamma \nabla \phi

The negative sign indicates that diffusion acts against the gradient.

In one dimension, the diffusive transport rate through an area AA is

Jd=−ΓAdϕdxJ_d = -\Gamma A \frac{d\phi}{dx}

If ϕ\phi increases in the positive xx direction, then dϕ/dxd\phi/dx is positive and the diffusive flux is directed in the negative xx direction.

2.3 Total transport flux

Define the total flux in the positive xx direction as

J=Fϕ−ΓAdϕdxJ = F\phi - \Gamma A \frac{d\phi}{dx}

where

F=ρuAF = \rho u A

is the mass flow rate through the face.

For steady transport without sources, conservation requires

dJdx=0\frac{dJ}{dx} = 0

Therefore,

ddx(Fϕ−ΓAdϕdx)=0\frac{d}{dx} \left( F\phi - \Gamma A \frac{d\phi}{dx} \right) = 0

For constant FF, Γ\Gamma, and AA, this becomes

Fdϕdx=ΓAd2ϕdx2F\frac{d\phi}{dx} = \Gamma A\frac{d^2\phi}{dx^2}

This equation describes the competition between convection and diffusion.


3. From the differential equation to a finite-volume equation

The finite-volume method starts by integrating the conservation equation over a control volume.

For a one-dimensional cell extending from its west face ww to its east face ee,

∫xwxedJdx dx=0\int_{x_w}^{x_e} \frac{dJ}{dx}\,dx = 0

Applying the fundamental theorem of calculus gives

Je−Jw=0J_e - J_w = 0

where JeJ_e and JwJ_w are the total fluxes through the east and west faces.

This equation has a direct physical interpretation:

The net flux leaving a steady control volume must be zero when there are no sources or sinks.

For a cell-centred finite-volume method, the cell value is stored at the cell centre, while fluxes are evaluated at its faces.

For cell PP, with west neighbour WW and east neighbour EE,

Je−Jw=0J_e - J_w = 0

The central numerical task is to express both face fluxes using the unknown cell-centred values.

3.1 Cell-centred mesh

Consider a uniform one-dimensional domain of length LL divided into NN cells.

The cell width is

Δx=LN\Delta x = \frac{L}{N}

The centre of cell ii is located at

xi=(i−12)Δxx_i = \left(i-\frac{1}{2}\right)\Delta x

for i=1,…,Ni=1,\ldots,N.

The scalar values are

ϕ1,ϕ2,…,ϕN\phi_1,\phi_2,\ldots,\phi_N

The west and east boundary values are denoted by ϕL\phi_L and ϕR\phi_R.

The distance from a boundary face to the adjacent cell centre is Δx/2\Delta x/2, whereas the distance between neighbouring cell centres is Δx\Delta x.

This distinction is essential when calculating diffusive fluxes at boundaries.


4. Discretizing the diffusive flux

Consider an internal face between cells PP and EE.

Using a linear approximation to the gradient,

dϕdx∣e≈ϕE−ϕPΔx\left.\frac{d\phi}{dx}\right|_e \approx \frac{\phi_E-\phi_P}{\Delta x}

The diffusive flux at this face is

Jd,e=−ΓAϕE−ϕPΔxJ_{d,e} = -\Gamma A \frac{\phi_E-\phi_P}{\Delta x}

Define the diffusion conductance

D=ΓAΔxD = \frac{\Gamma A}{\Delta x}

Then

Jd,e=D(ϕP−ϕE)J_{d,e}=D(\phi_P-\phi_E)

The conductance DD measures the strength of diffusion across the face.

A large conductance can result from a large diffusion coefficient or face area, or from a small distance between cell centres.

4.1 Diffusion at the boundaries

For a fixed-value boundary, the distance between the boundary face and the adjacent cell centre is Δx/2\Delta x/2.

The boundary conductance is therefore

Db=ΓAΔx/2D_b = \frac{\Gamma A}{\Delta x/2}

or

Db=2ΓAΔx=2DD_b = \frac{2\Gamma A}{\Delta x}=2D

for a uniform grid with constant properties.

At the west boundary, the total flux is

Jw=FϕL−Db(ϕ1−ϕL)J_w = F\phi_L-D_b(\phi_1-\phi_L)

At the east boundary, it is

Je=FϕR−Db(ϕR−ϕN)J_e = F\phi_R-D_b(\phi_R-\phi_N)

These expressions use the prescribed boundary value for the convective flux at the boundary face and a half-cell gradient for diffusion.

Important: A fixed-value condition specifies the scalar value at the boundary face. It is not the same as setting the first or last cell-centre value equal to that boundary value.


5. Discretizing the convective flux

The convective flux through a face is

Jc,e=FϕeJ_{c,e}=F\phi_e

The scalar value ϕe\phi_e must be estimated from the neighbouring cell values. This is where the choice of numerical scheme enters.

Two foundational choices are central differencing and first-order upwind differencing.

5.1 Central differencing

Central differencing approximates the face value by linear interpolation.

For a uniform grid,

ϕe≈ϕP+ϕE2\phi_e \approx \frac{\phi_P+\phi_E}{2}

The convective flux becomes

Jc,e=FϕP+ϕE2J_{c,e} = F\frac{\phi_P+\phi_E}{2}

Combining convection and diffusion gives

Je=FϕP+ϕE2+D(ϕP−ϕE)J_e = F\frac{\phi_P+\phi_E}{2} + D(\phi_P-\phi_E)

Rearranging,

Je=(D+F2)ϕP+(F2−D)ϕEJ_e = \left(D+\frac{F}{2}\right)\phi_P + \left(\frac{F}{2}-D\right)\phi_E

Define the face coefficients

cP=D+F2c_P = D+\frac{F}{2} cE=F2−Dc_E = \frac{F}{2}-D

Then

Je=cPϕP+cEϕEJ_e=c_P\phi_P+c_E\phi_E

Central differencing is second-order accurate for smooth fields on a uniform grid, but it may produce oscillations when convection dominates diffusion.

5.2 First-order upwind differencing

Upwind differencing selects the scalar value from the upstream side of the face.

For positive flow, F≥0F\geq 0, the fluid moves from west to east. The upstream value is ϕP\phi_P:

ϕe=ϕP\phi_e=\phi_P

Therefore,

Je=FϕP+D(ϕP−ϕE)J_e=F\phi_P+D(\phi_P-\phi_E)

or

Je=(D+F)ϕP−DϕEJ_e=(D+F)\phi_P-D\phi_E

The coefficients are

cP=D+Fc_P=D+F cE=−Dc_E=-D

For negative flow, the upstream cell is on the east side, so ϕe=ϕE\phi_e=\phi_E. The corresponding flux is

Je=DϕP+(F−D)ϕEJ_e=D\phi_P+(F-D)\phi_E

The implementation must therefore account for the direction of flow rather than assuming that velocity is always positive.

5.3 Comparing the schemes

PropertyCentral differencingFirst-order upwind
Face valueLinear interpolationUpstream cell value
Accuracy on a uniform gridSecond order for smooth fieldsFirst order
Numerical diffusionUsually lowerUsually higher
Robustness in convection-dominated flowsCan oscillateGenerally more robust
Main limitationMay lose boundednessCan smear gradients

Neither scheme is universally best. The appropriate choice depends on the physics, mesh resolution, desired accuracy, and stability requirements.


6. The cell Peclet number

The relative strength of convection and diffusion can be measured using the cell Peclet number:

Pe=FDPe = \frac{F}{D}

For constant properties and positive velocity,

Pe=ρuΔxΓPe = \frac{\rho u\Delta x}{\Gamma}

This dimensionless number helps explain the behaviour of convection–diffusion schemes.

  • If ∣Pe∣|Pe| is small, diffusion is relatively strong.
  • If ∣Pe∣|Pe| is large, convection is relatively strong.
  • If Pe=0Pe=0, the equation contains no convection.

For the standard one-dimensional, uniform-grid central-difference finite-volume formulation with constant coefficients, the internal off-diagonal coefficients remain non-negative in the conventional coefficient form when

∣Pe∣≤2|Pe|\leq 2

When this condition is violated, central differencing can lose the coefficient properties associated with bounded solutions and may produce nonphysical oscillations.

This is a scheme-specific criterion, not a universal stability condition for every CFD discretization.

Upwind differencing is more robust for large cell Peclet numbers, but its additional numerical diffusion can reduce accuracy.


7. Deriving the discrete linear system

The finite-volume equation for each cell is

Je−Jw=0J_e-J_w=0

For an internal face, write the total flux as

Je=cPϕP+cEϕEJ_e=c_P\phi_P+c_E\phi_E

The exact values of cPc_P and cEc_E depend on the chosen convection scheme.

For a cell-centred mesh with fixed-value boundary conditions, assembling all face fluxes produces a linear system:

Aϕ=b\mathbf{A}\boldsymbol{\phi}=\mathbf{b}

For a one-dimensional nearest-neighbour discretization, the matrix is tridiagonal:

[a1u10⋯0l2a2u2⋯00l3a3⋱0⋮⋮⋱⋱uN−1000lNaN][ϕ1ϕ2ϕ3⋮ϕN]=[b1b2b3⋮bN]\begin{bmatrix} a_1 & u_1 & 0 & \cdots & 0\\ l_2 & a_2 & u_2 & \cdots & 0\\ 0 & l_3 & a_3 & \ddots & 0\\ \vdots & \vdots & \ddots & \ddots & u_{N-1}\\ 0 & 0 & 0 & l_N & a_N \end{bmatrix} \begin{bmatrix} \phi_1\\ \phi_2\\ \phi_3\\ \vdots\\ \phi_N \end{bmatrix} = \begin{bmatrix} b_1\\ b_2\\ b_3\\ \vdots\\ b_N \end{bmatrix}

Here:

  • aia_i are diagonal coefficients.
  • lil_i are lower-diagonal coefficients.
  • uiu_i are upper-diagonal coefficients.
  • bib_i contains contributions from prescribed boundary values and any source terms.

Because each internal face is shared by two cells, its flux contributes with opposite signs to the neighbouring cell equations. This is how finite volume preserves local conservation.

7.1 Internal-face assembly

Suppose an internal face lies between cells ii and i+1i+1 and its flux is

Jf=cLϕi+cRϕi+1J_f=c_L\phi_i+c_R\phi_{i+1}

The flux contributes positively to the east face of cell ii:

Ai,i+=cLA_{i,i}\mathrel{+}=c_L Ai,i+1+=cRA_{i,i+1}\mathrel{+}=c_R

It contributes negatively to the west face of cell i+1i+1:

Ai+1,i−=cLA_{i+1,i}\mathrel{-}=c_L Ai+1,i+1−=cRA_{i+1,i+1}\mathrel{-}=c_R

The same numerical flux is used on both sides of the face. This is a key conservation principle.

7.2 Boundary assembly

For the west boundary,

Jw=−Dbϕ1+(F+Db)ϕLJ_w=-D_b\phi_1+(F+D_b)\phi_L

Because the cell equation contains −Jw-J_w, the matrix diagonal receives +Db+D_b and the right-hand side receives

b1+=(F+Db)ϕLb_1\mathrel{+}=(F+D_b)\phi_L

For the east boundary,

Je=DbϕN+(F−Db)ϕRJ_e=D_b\phi_N+(F-D_b)\phi_R

The final cell equation therefore receives a diagonal contribution of +Db+D_b and a right-hand-side contribution

bN+=(Db−F)ϕRb_N\mathrel{+}=(D_b-F)\phi_R

These terms are included in the C++ implementation below.


8. Building the C++ solver

We will implement a standalone one-dimensional solver with the following features:

  • Uniform, cell-centred mesh.
  • Constant density, velocity, diffusion coefficient, and cross-sectional area.
  • Steady convection–diffusion with no volumetric source.
  • Fixed scalar values at both boundary faces.
  • Central-difference or first-order upwind interpolation.
  • Tridiagonal matrix assembly.
  • Thomas algorithm for the linear system.
  • Comparison with an analytical solution.
  • CSV output for plotting and verification.

The implementation deliberately separates the numerical operations so that each part can later become a component in a larger CFD framework.

8.1 Governing equation and assumptions

We solve

ddx(Fϕ−ΓAdϕdx)=0\frac{d}{dx} \left( F\phi-\Gamma A\frac{d\phi}{dx} \right)=0

with

ϕ(0)=ϕL\phi(0)=\phi_L

and

ϕ(L)=ϕR\phi(L)=\phi_R

The mass flow rate F=ρuAF=\rho u A and the diffusion coefficient Γ\Gamma are constant.

The analytical solution for nonzero velocity is

ϕ(x)=ϕL+(ϕR−ϕL)exp⁡(PeLx/L)−1exp⁡(PeL)−1\phi(x)= \phi_L+ (\phi_R-\phi_L) \frac{\exp(Pe_L x/L)-1} {\exp(Pe_L)-1}

where

PeL=FLΓA=ρuLΓPe_L=\frac{FL}{\Gamma A} =\frac{\rho uL}{\Gamma}

is the domain Peclet number.

When F=0F=0, the solution reduces to a linear profile:

ϕ(x)=ϕL+(ϕR−ϕL)xL\phi(x)=\phi_L+(\phi_R-\phi_L)\frac{x}{L}

The analytical solution is useful for checking the implementation. A correct numerical method should approach it as the mesh is refined, subject to the accuracy of the selected scheme.

8.2 Complete C++ implementation

Save the following code as convection_diffusion_1d.cpp.

#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>

enum class ConvectionScheme
{
    Central,
    Upwind
};

struct Parameters
{
    int cells = 100;

    double length = 1.0;
    double area = 1.0;

    double density = 1.0;
    double velocity = 0.5;
    double diffusivity = 0.1;

    double phiLeft = 1.0;
    double phiRight = 0.0;

    ConvectionScheme scheme = ConvectionScheme::Upwind;
};

struct LinearSystem
{
    // lower[i] is A(i, i-1); lower[0] is unused.
    // upper[i] is A(i, i+1); upper[N-1] is unused.
    std::vector<double> lower;
    std::vector<double> diagonal;
    std::vector<double> upper;
    std::vector<double> rhs;
};

struct FaceCoefficients
{
    double left;
    double right;
};

void validate(const Parameters& p)
{
    if (p.cells < 2)
    {
        throw std::invalid_argument(
            "At least two cells are required.");
    }

    if (!(p.length > 0.0) ||
        !(p.area > 0.0) ||
        !(p.density > 0.0) ||
        !(p.diffusivity > 0.0))
    {
        throw std::invalid_argument(
            "Length, area, density, and diffusivity "
            "must be positive.");
    }

    if (!std::isfinite(p.velocity) ||
        !std::isfinite(p.phiLeft) ||
        !std::isfinite(p.phiRight))
    {
        throw std::invalid_argument(
            "Velocity and boundary values must be finite.");
    }
}

FaceCoefficients internalFaceCoefficients(
    double massFlux,
    double diffusionConductance,
    ConvectionScheme scheme)
{
    const double F = massFlux;
    const double D = diffusionConductance;

    if (scheme == ConvectionScheme::Central)
    {
        // J = F * (phiL + phiR) / 2
        //     + D * (phiL - phiR)
        return {
            D + 0.5 * F,
            0.5 * F - D
        };
    }

    // First-order upwind interpolation.
    if (F >= 0.0)
    {
        // Flow travels from left to right:
        // phi_face = phi_left.
        return {
            D + F,
            -D
        };
    }

    // Flow travels from right to left:
    // phi_face = phi_right.
    return {
        D,
        F - D
    };
}

LinearSystem assemble(const Parameters& p)
{
    validate(p);

    const int N = p.cells;
    const double dx = p.length / N;

    // Positive F means flow in the positive x direction.
    const double F =
        p.density * p.velocity * p.area;

    // Internal face conductance.
    const double D =
        p.diffusivity * p.area / dx;

    // Boundary face conductance:
    // boundary-to-cell-centre distance is dx / 2.
    const double Db = 2.0 * D;

    LinearSystem system{
        std::vector<double>(N, 0.0),
        std::vector<double>(N, 0.0),
        std::vector<double>(N, 0.0),
        std::vector<double>(N, 0.0)
    };

    // West boundary:
    //
    // J_w = -Db * phi_1 + (F + Db) * phiLeft
    //
    // The cell equation contains -J_w.
    system.diagonal[0] += Db;
    system.rhs[0] += (F + Db) * p.phiLeft;

    // East boundary:
    //
    // J_e = Db * phi_N + (F - Db) * phiRight
    //
    // The cell equation contains +J_e.
    system.diagonal[N - 1] += Db;
    system.rhs[N - 1] +=
        (Db - F) * p.phiRight;

    // Assemble each internal face exactly once.
    for (int i = 0; i < N - 1; ++i)
    {
        const FaceCoefficients c =
            internalFaceCoefficients(
                F, D, p.scheme);

        // Flux at the face between cell i and cell i+1:
        //
        // J_f = c.left * phi_i
        //     + c.right * phi_(i+1)

        // Add the flux to the east face of cell i.
        system.diagonal[i] += c.left;
        system.upper[i] += c.right;

        // Subtract the same flux from the west face
        // of cell i+1.
        system.lower[i + 1] -= c.left;
        system.diagonal[i + 1] -= c.right;
    }

    return system;
}

std::vector<double> solveThomas(LinearSystem system)
{
    const int N =
        static_cast<int>(system.diagonal.size());

    if (N == 0)
    {
        throw std::invalid_argument(
            "Cannot solve an empty linear system.");
    }

    // Forward elimination.
    for (int i = 1; i < N; ++i)
    {
        const double pivot =
            system.diagonal[i - 1];

        if (std::abs(pivot) <
            100.0 * std::numeric_limits<double>::epsilon())
        {
            throw std::runtime_error(
                "Near-zero pivot in Thomas algorithm.");
        }

        const double factor =
            system.lower[i] / pivot;

        system.diagonal[i] -=
            factor * system.upper[i - 1];

        system.rhs[i] -=
            factor * system.rhs[i - 1];
    }

    const double finalPivot =
        system.diagonal[N - 1];

    if (std::abs(finalPivot) <
        100.0 * std::numeric_limits<double>::epsilon())
    {
        throw std::runtime_error(
            "Near-zero final pivot in Thomas algorithm.");
    }

    // Back substitution.
    std::vector<double> phi(N, 0.0);

    phi[N - 1] =
        system.rhs[N - 1] /
        system.diagonal[N - 1];

    for (int i = N - 2; i >= 0; --i)
    {
        phi[i] =
            (system.rhs[i] -
             system.upper[i] * phi[i + 1]) /
            system.diagonal[i];
    }

    return phi;
}

double analyticalSolution(
    double x,
    const Parameters& p)
{
    const double Pe =
        p.density * p.velocity * p.length /
        p.diffusivity;

    const double deltaPhi =
        p.phiRight - p.phiLeft;

    if (std::abs(Pe) < 1.0e-8)
    {
        return p.phiLeft +
            deltaPhi * x / p.length;
    }

    // expm1(z) evaluates exp(z) - 1 more accurately
    // when z is close to zero.
    const double numerator =
        std::expm1(Pe * x / p.length);

    const double denominator =
        std::expm1(Pe);

    return p.phiLeft +
        deltaPhi * numerator / denominator;
}

void writeCSV(
    const Parameters& p,
    const std::vector<double>& phi,
    const std::string& filename)
{
    std::ofstream file(filename);

    if (!file)
    {
        throw std::runtime_error(
            "Could not open output file: " + filename);
    }

    file << "x,phi_numerical,phi_analytical,error\n";
    file << std::setprecision(12);

    const double dx = p.length / p.cells;

    for (int i = 0; i < p.cells; ++i)
    {
        const double x =
            (i + 0.5) * dx;

        const double exact =
            analyticalSolution(x, p);

        const double error =
            phi[i] - exact;

        file << x << ','
             << phi[i] << ','
             << exact << ','
             << error << '\n';
    }
}

int main(int argc, char* argv[])
{
    try
    {
        Parameters p;

        // Usage:
        // ./convection_diffusion_1d [cells] [central|upwind]
        if (argc >= 2)
        {
            p.cells = std::stoi(argv[1]);
        }

        if (argc >= 3)
        {
            const std::string scheme = argv[2];

            if (scheme == "central")
            {
                p.scheme = ConvectionScheme::Central;
            }
            else if (scheme == "upwind")
            {
                p.scheme = ConvectionScheme::Upwind;
            }
            else
            {
                throw std::invalid_argument(
                    "Scheme must be 'central' or 'upwind'.");
            }
        }

        validate(p);

        const LinearSystem system = assemble(p);

        const std::vector<double> phi =
            solveThomas(system);

        const double dx =
            p.length / p.cells;

        double maxError = 0.0;
        double sumSquaredError = 0.0;

        for (int i = 0; i < p.cells; ++i)
        {
            const double x =
                (i + 0.5) * dx;

            const double exact =
                analyticalSolution(x, p);

            const double error =
                phi[i] - exact;

            maxError = std::max(
                maxError, std::abs(error));

            sumSquaredError += error * error;
        }

        const double rmsError =
            std::sqrt(
                sumSquaredError / p.cells);

        const double domainPe =
            p.density * p.velocity * p.length /
            p.diffusivity;

        const double cellPe =
            p.density * p.velocity * dx /
            p.diffusivity;

        writeCSV(p, phi, "convection_diffusion.csv");

        std::cout << std::setprecision(8);
        std::cout << "1D steady convection-diffusion solver\n";
        std::cout << "Cells: " << p.cells << '\n';
        std::cout << "Scheme: "
                  << (p.scheme == ConvectionScheme::Central
                      ? "central"
                      : "upwind")
                  << '\n';

        std::cout << "Domain Peclet number: "
                  << domainPe << '\n';

        std::cout << "Cell Peclet number: "
                  << cellPe << '\n';

        std::cout << "Maximum absolute error: "
                  << maxError << '\n';

        std::cout << "RMS error: "
                  << rmsError << '\n';

        std::cout
            << "Wrote convection_diffusion.csv\n";

        return 0;
    }
    catch (const std::exception& e)
    {
        std::cerr << "Error: " << e.what() << '\n';
        return 1;
    }
}

8.3 Compile and run

With a C++17-compatible compiler, compile using:

g++ -std=c++17 -O2 -Wall -Wextra -pedantic \
    convection_diffusion_1d.cpp \
    -o convection_diffusion_1d

Run the upwind scheme on 100 cells:

./convection_diffusion_1d 100 upwind

Run the central-difference scheme on the same mesh:

./convection_diffusion_1d 100 central

On Windows with MinGW, the commands are similar, but the executable is typically named convection_diffusion_1d.exe.

The solver writes a CSV file containing the cell-centre coordinates, numerical solution, analytical solution, and pointwise error.

Expected behaviour: both schemes should produce finite results for the default parameters. Their errors will differ because they use different approximations for convective transport. Do not assume that the error must decrease by exactly a factor of two when the cell count doubles; the observed convergence depends on the scheme, boundary treatment, and mesh resolution.


9. Understanding the implementation

9.1 Why are the face coefficients returned by a function?

The function internalFaceCoefficients() represents the numerical flux independently of the matrix assembly.

For central differencing,

Jf=(D+F2)ϕL+(F2−D)ϕRJ_f= \left(D+\frac{F}{2}\right)\phi_L + \left(\frac{F}{2}-D\right)\phi_R

For upwind differencing with positive flow,

Jf=(D+F)ϕL−DϕRJ_f=(D+F)\phi_L-D\phi_R

Both schemes return two coefficients, but those coefficients differ because the approximation of the convective face value differs.

This design allows another scheme to be introduced without rewriting the entire solver.

For example, a future implementation could add a bounded higher-resolution scheme while leaving the mesh, boundary treatment, and linear solver unchanged.

9.2 Why is each internal face assembled once?

An internal face connects two neighbouring control volumes. The flux leaving one cell enters the other cell with the opposite sign.

If the flux is

Jf=cLϕL+cRϕRJ_f=c_L\phi_L+c_R\phi_R

then the left cell receives +Jf+J_f in its east-face contribution, while the right cell receives −Jf-J_f in its west-face contribution.

The assembly code uses exactly this relationship.

Computing one shared flux expression prevents the two neighbouring cells from using inconsistent versions of the same physical transfer.

9.3 Why is the boundary conductance doubled?

The distance from the boundary face to the adjacent cell centre is half the normal cell width.

The diffusive conductance is inversely proportional to the distance:

Db=ΓAΔx/2=2DD_b=\frac{\Gamma A}{\Delta x/2}=2D

Using DD rather than 2D2D at these faces would underestimate the diffusive boundary contribution for this uniform, cell-centred discretization.

9.4 Why does the Thomas algorithm work here?

The one-dimensional discretization connects each cell only to its immediate neighbours. The resulting matrix is tridiagonal.

The Thomas algorithm solves this system using forward elimination followed by back substitution.

Its computational cost is proportional to the number of cells, O(N)O(N), rather than the O(N3)O(N^3) cost associated with a generic dense direct solve.

The method is appropriate for this tridiagonal system when its pivots remain nonzero. It is not a general replacement for the sparse linear solvers required by large multidimensional CFD problems.


10. Verification against the analytical solution

Verification asks whether the numerical implementation correctly solves the mathematical model that was specified.

For this module, the analytical solution gives us an independent reference for the discrete results.

10.1 Error metrics

Let ϕi\phi_i be the numerical solution and ϕiexact\phi_i^{\mathrm{exact}} the analytical solution at the centre of cell ii.

The pointwise error is

ei=ϕi−ϕiexacte_i=\phi_i-\phi_i^{\mathrm{exact}}

The maximum absolute error is

E∞=max⁡i∣ei∣E_\infty=\max_i |e_i|

The root-mean-square error is

ERMS=1N∑i=1Nei2E_{\mathrm{RMS}} = \sqrt{\frac{1}{N}\sum_{i=1}^{N}e_i^2}

These measures capture different aspects of the discrepancy. The maximum error highlights the largest local deviation, while the RMS error measures the overall magnitude of the error across the cells.

10.2 Mesh-refinement study

Run each scheme with several cell counts:

./convection_diffusion_1d 25 upwind
./convection_diffusion_1d 50 upwind
./convection_diffusion_1d 100 upwind
./convection_diffusion_1d 200 upwind

Repeat with central differencing:

./convection_diffusion_1d 25 central
./convection_diffusion_1d 50 central
./convection_diffusion_1d 100 central
./convection_diffusion_1d 200 central

Record the RMS error from each run.

A typical convergence table is:

CellsCell widthRMS error
25L/25L/25Measure
50L/50L/50Measure
100L/100L/100Measure
200L/200L/200Measure

Replace “Measure” with the values reported by your actual runs. The values should be measured rather than assumed.

For sufficiently smooth solutions and a properly resolved mesh, first-order upwind is expected to show approximately first-order spatial convergence, while central differencing can show approximately second-order spatial convergence under suitable conditions. Boundary treatment, Peclet number, and solution regularity can affect the observed rate.

10.3 Estimating the observed order

Suppose the mesh spacing is reduced by a factor of two, and the errors on the coarse and fine meshes are EhE_h and Eh/2E_{h/2}.

The observed order can be estimated as

pobs=ln⁡(Eh/Eh/2)ln⁡2p_{\mathrm{obs}} = \frac{\ln(E_h/E_{h/2})}{\ln 2}

For example, if the error decreases by approximately a factor of two, the observed order is close to one. If it decreases by approximately a factor of four, the observed order is close to two.

This estimate is meaningful only when both meshes are in the asymptotic convergence range and the errors are not dominated by round-off or other effects.

10.4 Conservation check

For the source-free steady equation, the total flux should be constant throughout the domain:

Je=JwJ_e=J_w

The numerical flux should be evaluated using the same scheme and boundary treatment used during assembly.

A useful extension is to calculate the flux through every face and report

ΔJ=max⁡fJf−min⁡fJf\Delta J = \max_f J_f-\min_f J_f

A large value of ΔJ\Delta J can indicate an error in flux evaluation, assembly, or the linear solve.

For a converged solution of the assembled system, flux imbalance should be small relative to the characteristic flux scale, subject to solver precision and the numerical conditioning of the problem.


11. Numerical diffusion and scheme behaviour

11.1 Why upwind can smear a solution

Upwind differencing uses the upstream cell value for the convective flux. This is robust, but it introduces additional numerical diffusion.

In a convection-dominated flow, that diffusion can broaden sharp gradients and make the computed field appear smoother than the physical solution.

For a smooth solution, the error should reduce with mesh refinement. However, a coarse mesh can obscure important features even when the linear system has been solved accurately.

11.2 Why central differencing can oscillate

Central differencing uses information from both sides of a face. It is less diffusive for smooth fields, but its coefficients can lose the properties needed to maintain bounded solutions when convection dominates diffusion.

This may produce overshoots or undershoots, such as values outside the range imposed by the boundary conditions.

An accurate linear-system solution does not guarantee a physically acceptable discretized solution. The discretization itself must also be appropriate.

11.3 What about higher-order schemes?

Professional CFD solvers often use higher-resolution schemes designed to balance accuracy and boundedness.

Examples include:

  • Total variation diminishing (TVD) schemes.
  • Flux-limiter methods.
  • Bounded linear-upwind schemes.
  • Other higher-order reconstruction methods.

These schemes typically use additional information from neighbouring cells and apply limiting strategies to control nonphysical oscillations.

They are valuable when resolving steep gradients, wakes, shear layers, and transported interfaces, but their implementation is more involved than the two foundational schemes in this module.


12. Practical testing strategy

A CFD implementation should be tested systematically rather than judged from one plausible-looking plot.

Test 1: Pure diffusion

Set

u=0u=0

The analytical solution is linear. Both central differencing and upwind differencing reduce to the same internal diffusive flux formula.

Check whether the numerical profile approaches the linear analytical solution and whether the flux remains constant.

Test 2: Positive convection

Use

u>0u>0

The flow travels from left to right. Verify that the upwind scheme selects the west-side cell value for internal convective faces.

Test 3: Negative convection

Use

u<0u<0

The flow travels from right to left. Verify that the upwind scheme selects the east-side cell value.

This test is particularly useful for catching sign errors in the convective flux.

Test 4: Mesh refinement

Increase the number of cells while keeping the physical parameters unchanged.

Check whether the numerical solution approaches the analytical solution and whether the observed convergence rate is consistent with the scheme.

Test 5: Boundary conditions

Check that the boundary values are used at the boundary faces and that the half-cell distance is included in the diffusive boundary conductance.

Do not simply force the first and last cell-centre values to equal the boundary-face values. Those are different locations on a cell-centred mesh.

Test 6: Linear-system residual

After solving, evaluate the residual of the assembled system:

r=Aϕ−b\mathbf{r}=\mathbf{A}\boldsymbol{\phi}-\mathbf{b}

A small residual indicates that the discrete linear equations have been solved accurately. It does not, by itself, establish that the discretization is accurate or that the mathematical model represents a real physical system.

Test 7: Boundedness

For the selected boundary values, inspect the minimum and maximum numerical values.

For example, when both boundary values lie between zero and one, investigate any numerical values outside that range. Such behaviour can indicate a non-monotone discretization, a boundary treatment issue, or an implementation error.

Central differencing is not guaranteed to remain bounded for arbitrary cell Peclet numbers.


13. Connecting the implementation to OpenFOAM

The operators implemented here are simplified versions of the transport operators used in professional finite-volume solvers.

For a scalar field ϕ\phi, a general transport equation may contain terms representing transient accumulation, convection, diffusion, and sources:

∂(ρϕ)∂t+∇⋅(ρuϕ)=∇⋅(Γ∇ϕ)+Sϕ\frac{\partial(\rho\phi)}{\partial t} + \nabla\cdot(\rho\mathbf{u}\phi) = \nabla\cdot(\Gamma\nabla\phi) + S_\phi

In OpenFOAM, operators are assembled using the finite-volume framework. For example, a schematic scalar transport equation may include expressions of the form:

fvm::ddt(rho, phi)
+ fvm::div(phiFlux, phi)
- fvm::laplacian(gamma, phi)
==
source;

This is illustrative rather than a complete, universally compilable equation. The field types, flux definitions, dimensions, solver setup, and boundary conditions must match the specific case. In particular, the name phi is often used for a face flux in OpenFOAM examples, so a scalar field and its flux should be given distinct names in actual code.

The key conceptual correspondence is:

This moduleFinite-volume solver concept
internalFaceCoefficients()Scheme-dependent face-flux discretization
assemble()Matrix and source-term assembly
solveThomas()Linear-system solution
analyticalSolution()Analytical benchmark
CSV errorsVerification and post-processing
Fixed-value face treatmentBoundary-condition contribution to the matrix

The OpenFOAM implementation handles much more than this example: multidimensional meshes, non-orthogonal corrections, variable properties, coupled boundary conditions, parallel communication, sparse matrices, and a wide range of discretization schemes.

The purpose of building this small solver is to understand the numerical principles beneath those abstractions.


14. Common implementation mistakes

Mistake 1: Reversing the diffusive flux sign

The diffusive flux is

Jd=−ΓAdϕdxJ_d=-\Gamma A\frac{d\phi}{dx}

For an internal face,

Jd=D(ϕP−ϕE)J_d=D(\phi_P-\phi_E)

Reversing this sign turns diffusion into anti-diffusion and can make the problem physically incorrect or numerically unstable.

Mistake 2: Using the wrong upwind cell

The upstream side depends on the sign of the mass flux FF, not on the cell index alone.

For positive FF, use the left cell. For negative FF, use the right cell.

Mistake 3: Using the wrong face distance

The distance between neighbouring cell centres is Δx\Delta x. The distance from a boundary face to its adjacent cell centre is Δx/2\Delta x/2.

The diffusive conductance must reflect the correct distance.

Mistake 4: Assembling a shared face twice

A shared internal face should contribute with opposite signs to its two neighbouring cell equations. Using inconsistent flux expressions on the two sides can destroy local conservation.

Mistake 5: Confusing solver convergence with numerical accuracy

A linear solver may produce a very small residual while the discretized solution remains inaccurate because the mesh is too coarse or the numerical scheme is unsuitable.

Check both algebraic convergence and discretization error.

Mistake 6: Trusting a plot without a benchmark

A smooth field is not proof of correctness. Compare the solution with an analytical or independently verified reference whenever possible.

Mistake 7: Ignoring units

The terms in the flux expression must be dimensionally consistent. For example, if ϕ\phi is dimensionless, both FϕF\phi and DϕD\phi have units of mass per time when F=ρuAF=\rho uA and D=ΓA/ΔxD=\Gamma A/\Delta x use a compatible scalar diffusivity.

If ϕ\phi represents temperature and Γ\Gamma is thermal conductivity, the diffusion coefficient and convective coefficient must instead be chosen consistently with the specific energy equation being solved.


15. Exercises

Work through the following exercises to develop a stronger understanding of the numerical method.

Exercise 1: Compare central and upwind schemes

Run both schemes with 100 cells using the default parameters.

Record the RMS error and compare the numerical profiles.

Explain why the two schemes produce different results even though they solve the same continuous equation.

Exercise 2: Change the cell Peclet number

Change the velocity from 0.50.5 to 2.02.0 while keeping the diffusivity unchanged.

Run the central and upwind schemes.

Determine the new cell Peclet number and inspect the results for overshoots or undershoots.

Exercise 3: Reverse the flow

Set the velocity to a negative value.

Confirm that the upwind scheme selects the correct upstream cell and explain how the boundary conditions interact with the reversed flow.

Exercise 4: Investigate numerical diffusion

Run the upwind scheme with 25, 50, 100, and 200 cells.

Plot the numerical and analytical solutions together. Describe how the numerical profile changes as the mesh is refined.

Exercise 5: Implement a source term

Extend the equation to include a constant source:

dJdx=Sϕ\frac{dJ}{dx}=S_\phi

The finite-volume balance becomes

Je−Jw=SϕAΔxJ_e-J_w=S_\phi A\Delta x

for a uniform volumetric source density SϕS_\phi.

Add the integrated source contribution to the right-hand side and derive the corresponding analytical solution for a simple test case.

Exercise 6: Add a zero-gradient boundary

Replace the fixed-value condition at the outlet with a zero-gradient condition:

dϕdx∣R=0\left.\frac{d\phi}{dx}\right|_R=0

Derive the resulting boundary-face flux and modify the matrix assembly. Be careful to distinguish the diffusive boundary contribution from the convective outflow contribution.

Exercise 7: Refactor the framework

Separate the implementation into classes or modules for:

  • Mesh geometry.
  • Scalar field storage.
  • Convection schemes.
  • Diffusion fluxes.
  • Boundary conditions.
  • Matrix assembly.
  • Linear solvers.
  • Verification and output.

The goal is to make it possible to add a new convection scheme without rewriting the mesh or linear solver.


16. Key takeaways

Convection and diffusion are fundamental building blocks of CFD. Their implementation requires more than writing down a differential equation: the equation must be integrated over control volumes, the face fluxes must be approximated, boundary conditions must be incorporated, and the resulting algebraic system must be solved.

The most important principles from this module are:

  1. Conservation comes first. Begin with the balance of fluxes through the control-volume faces.
  2. The face interpolation defines the scheme. Central and upwind differ in how the convective face value is estimated.
  3. Flow direction matters. An upwind scheme must select the upstream value according to the sign of the face mass flux.
  4. Boundary geometry matters. A cell-centred boundary face is half a cell width from the adjacent cell centre on a uniform grid.
  5. Assembly must preserve shared-face consistency. Each internal flux enters neighbouring equations with opposite signs.
  6. Accuracy must be verified. Compare against analytical solutions and perform mesh-refinement studies.
  7. A small solver is a learning instrument. It reveals the numerical structure that larger CFD software packages automate.

17. What’s next?

In Module 13, the natural next step is to develop higher-order convection schemes and flux limiters. First-order upwind is robust but diffusive, while central differencing can oscillate in convection-dominated problems. Higher-resolution schemes aim to improve accuracy without introducing unacceptable nonphysical oscillations.

The next module can build on the face-flux interface introduced here, add gradient reconstruction, and explore how numerical schemes balance accuracy, boundedness, and robustness.