24
One Dimensional Convection: Interpolation Models for CFD Gerald Recktenwald * January 24, 2012 Abstract The finite-volume method for numerical solutions of the one-dimensional convection-diffusion equation is described and demonstrated with Mat- lab. This well-known problem has an exact solution, which is used to compare the behavior and accuracy of the central difference and upwind difference schemes. Matlab codes for both schemes are developed and numerical solutions are presented on sequences of finer meshes. As the mesh size is reduced the dependency of the truncation error on mesh size for both schemes is verified. The existence and cause of oscillatory solu- tions for the central difference scheme are explained. The superior perfor- mance of the central difference method under suitable mesh refinement is demonstrated. 1 Introduction Finite volume methods are widely used in computational fluid dynamics (CFD) codes. The elementary finite volume method uses a cell-centered mesh and finite-difference approximations of first order derivatives. This paper shows how the finite volume method is applied to a model of convective transport: the one-dimensional convection-diffusion equation. There are two primary goals of this paper. The first is to expose the finite volume method. Readers interested in additional details, including application to the Navier-Stokes equations, should consult the classic text by Patankar [4]. Ferziger and Peri´ c [2] give a more up-to-date discussion of finite volume meth- ods, but without the low level details presented in this paper. Versteeg and Malalasekera [5] provide a detailed discussion of the topics described in this paper, although their presentation does not deal with the effect of non-uniform meshes. Abbott and Basco [1] provide a basic analysis of convection modeling for the transient version of the one-dimensional convection-diffusion equation. Wesseling [7] gives a mathematically rigorous treatment of the finite volume method, including a discussion of different approximations to the convective terms. The second goal of this paper is to introduce and compare the central dif- ference scheme and the upwind scheme for modeling the convective term in * Mechanical and Materials Engineering Department, Portland State University, Portland, OR, 97201, [email protected]

Convection Up Wind

Embed Size (px)

Citation preview

Page 1: Convection Up Wind

One Dimensional Convection:

Interpolation Models for CFD

Gerald Recktenwald∗

January 24, 2012

Abstract

The finite-volume method for numerical solutions of the one-dimensionalconvection-diffusion equation is described and demonstrated with Mat-lab. This well-known problem has an exact solution, which is used tocompare the behavior and accuracy of the central difference and upwinddifference schemes. Matlab codes for both schemes are developed andnumerical solutions are presented on sequences of finer meshes. As themesh size is reduced the dependency of the truncation error on mesh sizefor both schemes is verified. The existence and cause of oscillatory solu-tions for the central difference scheme are explained. The superior perfor-mance of the central difference method under suitable mesh refinement isdemonstrated.

1 Introduction

Finite volume methods are widely used in computational fluid dynamics (CFD)codes. The elementary finite volume method uses a cell-centered mesh andfinite-difference approximations of first order derivatives. This paper showshow the finite volume method is applied to a model of convective transport: theone-dimensional convection-diffusion equation.

There are two primary goals of this paper. The first is to expose the finitevolume method. Readers interested in additional details, including applicationto the Navier-Stokes equations, should consult the classic text by Patankar [4].Ferziger and Peric [2] give a more up-to-date discussion of finite volume meth-ods, but without the low level details presented in this paper. Versteeg andMalalasekera [5] provide a detailed discussion of the topics described in thispaper, although their presentation does not deal with the effect of non-uniformmeshes. Abbott and Basco [1] provide a basic analysis of convection modelingfor the transient version of the one-dimensional convection-diffusion equation.Wesseling [7] gives a mathematically rigorous treatment of the finite volumemethod, including a discussion of different approximations to the convectiveterms.

The second goal of this paper is to introduce and compare the central dif-ference scheme and the upwind scheme for modeling the convective term in

∗Mechanical and Materials Engineering Department, Portland State University, Portland,OR, 97201, [email protected]

Page 2: Convection Up Wind

2 THE CONVECTION-DIFFUSION EQUATION 2

0 0.2 0.4 0.6 0.8 10

0.1

0.2

0.3

0.4

0.5

0.6

0.7

0.8

0.9

1

x

φ

−50

−5

−1

0

1

5

50

Figure 1: Exact solution to Equation (1) subject to the boundary conditionsφ(0) = 1 and φ(1) = 0. Parameter labels on the curves are values of PeL.

transport equations. The one-dimensional convection-diffusion equation is acompact, though somewhat non-physical, model of transport of heat, mass andother passive scalars. Applying the finite volume method to this equation allowsdifferent schemes for approximating the convection term to be compared.

2 The Convection-Diffusion Equation

The one-dimensional convection-diffusion equation is

d

dx(uφ)− d

dx

(Γdφ

dx

)− S = 0 (1)

The dependent variable φ is a scalar that is transported by the velocity u, whichis constant. The diffusion coefficient is Γ, and S is a volumetric source term.

For S = 0 and the boundary conditions

φ(0) = φ0 φ(L) = φL, (2)

the exact solution to Equation (1) is

φ− φ0φL − φ0

=exp(ux/Γ)− 1

exp(PeL)− 1(3)

where

PeL =uL

Γ(4)

is the Peclet number, the dimensionless parameter that describes the relativestrength of convection (u) to diffusion (Γ/L).

Figure 1 shows a family of solutions to Equation (1) with boundary condi-tions φ(0) = 1 and φ(1) = 0. For large PeL, the φ distribution is nearly uniform

Page 3: Convection Up Wind

3 THE FINITE VOLUME MESH 3

except for a thin layer near the x = L boundary. Negative u (velocity fromright to left) causes the φ profile to be shifted to the left instead of the right.

As PeL → 0 the effect of convection disappears and the solution to Equa-tion (1), subject to the boundary conditions in (2), is

φ− φ0φL − φ0

=x

L(5)

When u = 0 and S = 0, Equation (1) becomes the one-dimensional Laplaceequation, which describes heat conduction through a slab with uniform con-ductivity. Equation (5) is the solution to the one-dimensional heat conductionproblem with fixed end temperatures.

3 The Finite Volume Mesh

In the finite difference method, the mesh is defined by the location of nodes inspace (and possibly time). In the finite volume method, the spatial domain ofthe physical problem is subdivided into non-overlapping cells or control volumes.A single node is located at the geometric centroid of the control volume1. In thefinite volume method, the numerical approximation is obtained by integratingthe governing equation over the control volume. The nodal volumes are used tocompute the flux of dependent variable from one control volume into the next.

Figure 2 shows a typical control volume in a Cartesian coordinate system.Since we are only concerned with one-dimensional diffusion problems, the nodesabove and below the control volume are not shown.

Figure 2 also introduces compass point notation. The node at xi is referredto as point P. Relative to P, the node at xi+1 is labeled E for east, and the nodeat xi−1 is labeled W for west. The cell face between P and E is at xe, and thecell face between W and P is at xw. The convention is that upper case letters(P, E, W) refer to the location of the nodes, and the lower case letters (e, w)refer to the cell faces.

The use of the dual notation may seem cumbersome at first. However,compass point notation is very convenient for the derivation of the discrete

1There are other ways to define the locations of nodes relative to the boundaries of thecontrol volume. Locating the node at the centroid is a popular scheme.

∆x

xi+1xi-1

P EW

xexw

xi

∆y

x

y

δxeδxw

Figure 2: One-dimensional control volume.

Page 4: Convection Up Wind

4 THE CENTRAL-DIFFERENCE FINITE VOLUME MODEL 4

δxe,2δxw,2

∆x2

i = 1 2 3

∆xm−1

δxe,m−1δxw,m−1

m −2 m−1 m. . .

. . .

Figure 3: A one-dimensional mesh used to solve Equation (1). The mesh isdepicted as uniform, but the finite volume method is not restricted to uniformmeshes.

approximation to Equation (1). The use of nodal indices such as i, i + 1, andi− 1 is still important, especially when implementing the finite volume methodin a computer code.

Figure 3 depicts a group of control volumes along the x axis. The left andright edges are the boundaries of the domain. Two nodes, i = 1 and i = m,are on the boundaries, and do not have cell volumes2. These nodes are used toimplement boundary conditions.

4 The Central-Difference Finite Volume Model

To obtain the finite volume model, Equation (1) is integrated over the controlvolume shown in Figure 2.∫ xe

xw

d(uφ)

dxdx−

∫ xe

xw

d

dx

(Γdφ

dx

)dx−

∫ xe

xw

S dx = 0 (6)

In the following sections, each term in this equation is evaluated and simplifiedseparately. The parts are then reassembled into a discrete equation relating φat node P to the φ values at nodes E and W.

4.1 The Diffusion Term

The second term in Equation (6) expresses the balance of transport by diffusioninto the control volume3. The integral can be evaluated exactly.∫ xe

xw

d

dx

(Γdφ

dx

)dx =

(Γdφ

dx

)e

−(

Γdφ

dx

)w

(7)

The two diffusive fluxes are replaced by finite-difference approximations(Γdφ

dx

)e

≈ ΓeφE − φPδxe

= De(φE − φP )

(Γdφ

dx

)w

≈ ΓwφP − φWδxw

= Dw(φP − φW )

2An alternative view is that the control volumes for i = 1 and i = m have zero width, andhence zero volume.

3For example, if φ = T (temperature) and Γ = k (thermal conductivity), the diffusion termis the net conduction of heat into the control volume.

Page 5: Convection Up Wind

4 THE CENTRAL-DIFFERENCE FINITE VOLUME MODEL 5

where

De =Γe

δxeDw =

Γw

δxw(8)

andδxe = xE − xP δxw = xP − xW . (9)

Remember that φP , φE , and φW are the values of φ at the nodes P, E, and Win Figure 2. These are the discrete unknowns that are obtained by solution ofthe finite volume model equations.

In this paper only the case of uniform Γ is considered, so Γe = Γw = Γ.Nonuniform Γ is easily handled by the finite volume method [4]. Using theterms just defined, Equation (7) becomes∫ xe

xw

∂x

(Γ∂φ

∂x

)dx ≈ De(φE − φP )−Dw(φP − φW ) (10)

4.2 The Source Term

The discrete contribution of the source term is obtained by assuming that S hasthe uniform value of SP throughout the control volume. Thus,∫ xe

xw

S dx ≈ SP ∆xp. (11)

The distribution of SP is supplied as an input to the model. The finite volumemethod also allows source terms to depend on φ. (See, e.g., [4]).

4.3 The Convection Term

The convective term in Equation (6) can be integrated once exactly.∫ xe

xw

d(uφ)

dxdx = (uφ)e − (uφ)w (12)

To evaluate the right hand side of the preceding expression, the values of φe andφw need to be estimated. In the finite volume method, the values of φ are storedonly at the nodes P, E, and W. The method for determining an interface value(say, φe) from the nodal values (say, φP and φE) has important consequencesfor the accuracy of the numerical model of Equation (1).

A straightforward method for estimating φe in terms of the nodal values φEand φP is linear interpolation, as depicted in Figure 4. The linear interpolationformula can be written

φe = βeφE + (1− βe)φP (13)

where

βe =xe − xPxE − xP

(14)

Equations (13) and (14) constitute the central difference scheme for approxi-mating the derivatives4.

4The title comes from the finite-difference approach to modeling Equation (1). The firstorder central difference approximation to the convective term at the interface (x = xe) is

d(uφ)

dx

∣∣∣∣e

≈(uφ)E − (uφ)P

xE − xP

Page 6: Convection Up Wind

4 THE CENTRAL-DIFFERENCE FINITE VOLUME MODEL 6

xE

xW

xP

xexw

ϕW

ϕP ϕ

E

Figure 4: Linear interpolation to obtain interface values φw and φe for thecentral difference approximation.

Using linear interpolation to estimate φw in terms of φW and φP gives

φw = βwφW + (1− βw)φP (15)

where

βw =xP − xwxP − xW

. (16)

If the mesh is uniform and the nodes are located midway between the cell faces,then βw = βe = 1/2.

Substituting Equation (13) and Equation (15) into Equation (12) and rear-ranging gives∫ xe

xw

d(uφ)

dxdx = ueβe(φE − φP )− uwβw(φW − φP ) + ueφP − uwφP (17)

The last two terms in the preceding equation cancel because u is a uniformparameter, i.e. ue = uw. Therefore, Equation (17) simplifies to5∫ xe

xw

d(uφ)

dxdx = ueβe(φE − φP )− uwβw(φW − φP ) (18)

4.4 The Discrete φ Equation

Substituting Equation (10), Equation (11) and Equation (18) into Equation (6)and simplifying gives

−aEφE + aPφP − aWφW = b (19)

5Repeating this derivation for two- or three-dimensional convection models requires invoca-tion of the discrete form of the continuity equation. The one-dimensional continuity equationis du/dx = 0. Integrating this equation over the control volume gives ue − uw = 0. Thiscomputation is not necessary in the one-dimensional case, because u is a fixed parameter andu = ue = uw.

Page 7: Convection Up Wind

4 THE CENTRAL-DIFFERENCE FINITE VOLUME MODEL 7

where

aE =1

∆xP(De − ueβe) (20)

aW =1

∆xP(Dw + uwβw) (21)

aP = aE + aW (22)

b = SP (23)

Equation (19) applies to each internal node in the computational domain.The system of equations for m nodes (including boundary nodes) can be

written in matrix notation as

aP,1 −aE,1

−aW,2 aP,2 −aE,2

. . .. . .

. . .

−aW,i aP,i −aE,i

. . .. . .

. . .

−aW,m aP,m

φ1φ2...φi...φm

=

b1b2...bi...bm

(24)

The system is tridiagonal, and is easily solved with a direct method called thetridiagonal matrix algorithm.

4.5 Boundary Conditions

The boundary conditions in Equation (2) are enforced by modifying the coef-ficients in Equation (24). For nodes 2 through m − 1, Equations (20) through(23) define the coefficients in the matrix and the right hand side vector. Imple-mentation of boundary conditions only concerns the first row and the last rowin Equation (24). Those equations are

aP,1φ1 − aE,1φ2 = b1

−aW,mφm−1 + aP,mφm = bm

Setting aP,1 = 1, aE,1 = 0, b1 = φ0, and aW,m = 0, aP,m = 1, bm = φL. givesthe trivial equations

φ1 = φ0

φm = φL.

Thus, modifying the coefficients and source terms of the equations for the bound-ary nodes allows the values those nodes to be specified. When the modified sys-tem of equations is solved, the boundary nodes are fixed, and the values of theinterior nodes are consistent with the specified boundary values. It is relativelystraightforward to modifying the boundary node equations for other types ofboundary conditions. The procedures for doing so will not be discussed here.

Page 8: Convection Up Wind

4 THE CENTRAL-DIFFERENCE FINITE VOLUME MODEL 8

4.6 Matlab Implementation

Numerical solutions to Equations (1) and (2) are obtained with the Matlabfunctions central1D and demoConvect1D. The source codes for central1d anddemoConvect1D are given in Listing 1 and Listing 2 at the end of this article.

The central1D function defines a one-dimensional mesh and evaluates thefinite volume coefficients in Equation (20) through Equation (23) for given valuesof u, Γ, and S. The demoConvect1D function calls central1D or upwind1D

(described later) to obtain the finite volume coefficients. demoConvect1D thenuses the tridiagSolve function from the NMM toolbox. The finite volumesolution is then compared with the exact solution.

4.7 Measuring the Truncation Error

Since the exact solution is given by Equation (3), the truncation error of thenumerical solution can be computed. Designate the exact solution at cell i asφ(xi). The error at cell i obtained with the central difference scheme is

ec,i = φc,i − φ(xi)

where φc,i is the value of φ at cell i obtained with the central difference scheme,i.e.,, by the solution to Equation (24). The largest error in the domain is

maxi|ec,i| = ||ec||∞

The width of the internal control volumes in the domain is ∆x. ReplacingL with ∆x in Equation (4) gives the mesh Peclet number.

Pex =u∆x

Γ(25)

which describes the local strength of the convection and diffusion terms for anindividual control volume. PeL is the only true parameter of Equation (1). Pexis an artifact of the mesh used to obtain the numerical approximation to thesolution. As the mesh is refined, ∆x→ 0 and Pex → 0, while PeL is independentof the mesh.

4.8 Performance of the Central Difference Scheme

Running demoConvect1D with the default input parameters produces the plotin Figure 5. The numerical solution oscillates with increasing magnitude as xincreases toward 1. By any reasonable measure, this numerical solution is a verybad approximation to the exact solution.

The oscillations in the numerical solution can be reduced by solving theproblem with a finer mesh. For example

>> demoConvect1D(’CDS’,32)

produces the plot in Figure 6. Reducing the control volume width from ∆x = 0.1to ∆x = 0.0333 reduces the mesh Peclet number from 5 to 1.7. The centraldifference solution to Equation (1) will not oscillate as long as Pex < 2.

Page 9: Convection Up Wind

4 THE CENTRAL-DIFFERENCE FINITE VOLUME MODEL 9

0 0.2 0.4 0.6 0.8 10

0.5

1

1.5

x

φ

PeL = 50.0, Pex = 5.0

CDS scheme, Max error = 1.583

CDS solution

exact

Figure 5: Central difference solutions to Equation (1) for PeL = 50, Pex = 5.

0 0.2 0.4 0.6 0.8 10

0.5

1

1.5

x

φ

PeL = 50.0, Pex = 1.7

CDS scheme, Max error = 0.268

CDS solution

exact

Figure 6: Central difference solutions to Equation (1) for PeL = 50, Pex = 1.7.

Page 10: Convection Up Wind

5 UPWIND DIFFERENCING: A CURE WITH A COST 10

4.9 Consequences of Negative Coefficients

The oscillatory numerical solution shown in Figure 5 can be explained by theexistence of negative aE or aW in Equation (19). Consider the possible valuestaken by aE , which is defined by Equation (20). For a uniform mesh, theinterpolation coefficient βe is

βe =∆xP /2

δxe

and Equation (20) can be rearranged as

aE =1

∆xP(De − ueβe) =

1

∆xP

(Γe

δxe− ue

∆xP /2

δxe

)

=Γe

∆xP δxe

(1− Pex

2

)Since Γe/(∆xP δxe) > 0 always, the magnitude of Pex determines the signof aE . Specifically, when Pex < 2, aE > 0, and when Pex ≥ 2, aE ≤ 0.When aE < 0, the eigenvalues of the coefficient matrix in Equation (24) becomecomplex, and the numerical solution oscillates. See, e.g. Hoffman [3, Chapter 14]or Wesseling [7, Chapter 4] for a proof.

The magnitude of Pex can always be kept below the threshold value of twoby choosing a sufficiently fine mesh. For one-dimensional problems, this is notan issue. However, this Pex limit is also true for two- and three-dimensionalproblems. In the early days of CFD, reducing the mesh spacing to guaranteePex < 2 was not always an option because memory was limited, and solutionson fine meshes took too much time. Modern computers have enough memoryand floating point performance that selecting a sufficiently fine mesh to mini-mize (or eliminate) oscillations is usually not a problem. Nonetheless, a morerobust formulation is still desirable for many practical problems, especially forexploratory calculations on coarse meshes.

5 Upwind Differencing: A Cure with a Cost

The existence of oscillatory solutions for Pex > 2 is a nagging problem for thecentral difference scheme. The oscillations can be completely eliminated with asurprisingly simple modification. Unfortunately, this simple modification resultsin a severe loss of accuracy in the computed result.

In § 4.9, it was asserted that the existence of a negative coefficients causesthe oscillation in the solution. A quick fix to this problem is to change theinterpolation scheme so that De − βeue > 0 for any combination of ue, ∆xPand Γe. The upwind scheme guarantees positive aE (and positive aW ) with thefollowing choice of βe and βw:

βe =

{0 if ue ≥ 0

1 if ue < 0(26)

βw =

{1 if uw ≥ 0

0 if uw < 0(27)

Page 11: Convection Up Wind

5 UPWIND DIFFERENCING: A CURE WITH A COST 11

xE

xW

xP

xexw

ϕW

ϕP ϕ

E

xE

xW

xP

xexw

ϕW

ϕP ϕ

E

ue > 0uw > 0 ue < 0uw < 0

Figure 7: Upwind interpolation to obtain interface values φw and φe. For clar-ity, we choose φW > φP > φE , though the magnitude of the φ values is notimportant. The sign of u determines the value of φ assumed at the interface.

Figure 7 provides a graphical representation of the upwind difference scheme.Compare the step-like φ(x) profiles for the upwind scheme in Figure 7 with thelinear profiles for the central difference scheme in Figure 4.

In the left half of Figure 7 the velocities are positive. When ue > 0, Equa-tion (26) and Equation (13) combine to give φe = φP . Thus, the value of φ atthe east interface of the control volume is taken to be the nearest nodal valueon the upwind side of the interface.

Similarly, when uw > 0, Equation (27) and Equation (15) give φw = φW .At both interfaces, the value of φ is determined by the upwind neighbor. Inthe right half of Figure 7 the sign of the velocities is reversed, and the upwindneighbors lie to the right of both interfaces.

5.1 Matlab Implementation

The coefficients of the upwind scheme are evaluated in the upwind1D function,in Listing 3. The substantial difference between upwind1D and central1d isthat the β coefficients are computed with Equations (26) and (27) instead ofEquations (14) and (16).

The upwind difference solutions corresponding to Figure 5 and Figure 6 areobtained with the following command line inputs

>> demoConvect1D(’UDS’)

>> demoConvect1D(’UDS’,32)

The output from the preceding commands is not shown here.The compConvect1D function in Listing 4 evaluates both the central differ-

ence and upwind difference solutions, and plots these solutions along with theexact solution. The following command line inputs create the plots in Figure 8.

>> compConvect1D

>> compConvect1D(32)

For both Pex = 5 and Pex = 1.7 the upwind difference scheme is free from oscil-lations. In addition, the upwind difference scheme produces a smaller truncationerror than the central difference scheme for both of these meshes.

Page 12: Convection Up Wind

5 UPWIND DIFFERENCING: A CURE WITH A COST 12

0 0.2 0.4 0.6 0.8 1−0.5

0

0.5

1

1.5

2

x

φ

PeL = 50.0, Pe

x = 5.0

||ec|| = 1.583, ||e

u|| = 0.204

CentralUpwindExact

0 0.2 0.4 0.6 0.8 1−0.5

0

0.5

1

1.5

2

x

φ

PeL = 50.0, Pe

x = 1.7

||ec|| = 0.268, ||e

u|| = 0.122

CentralUpwindExact

Figure 8: Numerical solutions to Equation (1) with the upwind difference schemeand the central difference scheme for two different mesh sizes. The cell Pecletnumber decreases as the number of cells increases.

Page 13: Convection Up Wind

6 EFFECT OF MESH REFINEMENT 13

6 Effect of Mesh Refinement

In the preceding section, the numerical solutions obtained with the upwindscheme are free of oscillations. Furthermore, the upwind solutions for Pex = 5and Pex = 1.7 have smaller measured truncation errors than the central dif-ference solutions. This apparent accuracy advantage is not true in all circum-stances, however.

Mathematical analysis shows that the truncation errors for the upwind dif-ference scheme and central difference scheme are O (∆x) and O

(∆x2

), respec-

tively. (See, Ferziger and Peric [2, § 4.4] for a straightforward analysis.) Thus,as the mesh is refined, we expect the error in the central difference solution todecrease much more rapidly than the error in the upwind solution.

Table 1 shows the results of mesh refinement for the upwind and centraldifference solutions to Equation (1). The same data is plotted in Figure 9. Thetable and plot are constructed with the refineConvect1D function in Listing 5.For large ∆x (large Pex) the upwind difference scheme has a smaller error thanthe central difference scheme. As ∆x and Pex are reduced, the error in thecentral difference solution is reduced much more rapidly than the error in theupwind solution.

The columns in Table 1 labeled “eu ratio” and “ec ratio” confirm the theo-retical prediction of truncation errors. For a given value of m (given row in thetable), the value in the eu ratio column is the ratio of ||eu||∞ for the precedingrow (previous m) to the value of ||eu||∞ for the current m. For example, form = 512

eu ratio =0.0320

0.0169= 1.89.

As ∆x→ 0 the values of m in subsequent rows differ by a factor of two. Theupwind scheme has a theoretical truncation error that is O (∆x). By halving thecontrol volume width (by doubling m) one expects the truncation error, whichis proportional to ||eu||∞, to be reduced by a factor of two. As m increases, thevalues in the eu ratio column are approaching two. The value of the eu ratio atlarge m is more representative of the truncation error because the truncationerror estimate holds as ∆x→ 0.

The central difference scheme has a theoretical truncation error that isO(∆x2

). Halving the control volume widths reduces the truncation error by a

factor of four, as indicated by the values in the last column of Table 1. Thus,although the upwind scheme is more accurate than the central difference schemeon the coarsest mesh, the improvement in accuracy as ∆x is reduced shows thatthe central difference scheme is superior.

6.1 Non-uniform Meshes

Uniform refinement of a uniform mesh is often not the best use of computa-tional resources (memory and processing time). For the one-dimensional prob-lem discussed in this article, the computational cost of mesh refinement is ofno practical concern. However, for industrial applications of CFD, non-uniformmeshes are often essential in order to obtain acceptably accurate results withmodest computing resources.

The basic idea of non-uniform mesh refinement is to use smaller controlvolume widths (smaller node spacing) in regions where the gradient of the de-

Page 14: Convection Up Wind

6 EFFECT OF MESH REFINEMENT 14

Table 1: Variation of error with mesh spacing for upwind and central differenceschemes. Numerical solutions obtained at PeL = 50. m − 2 is the number ofinternal control volumes (cells) in the model.

Upwind Central Difference

m ∆x Pex ||eu||∞ eu ratio ||ec||∞ ec ratio

8 0.166667 8.33 0.1780 3.4154

16 0.071429 3.57 0.1913 0.93 0.9534 3.58

32 0.033333 1.67 0.1225 1.56 0.2679 3.56

64 0.016129 0.81 0.0962 1.27 0.0714 3.75

128 0.007937 0.40 0.0569 1.69 0.0184 3.87

256 0.003937 0.20 0.0320 1.78 0.0047 3.93

512 0.001961 0.10 0.0169 1.89 0.0012 3.97

1023 0.000978 0.05 0.0087 1.94 0.0003 3.98

pendent variable is large. For the solution to the boundary value problem showngraphically in Figure 8, the steepest gradients are near the x = L boundary foru > 0 (or PeL > 0). We expect that locally refining the mesh near x = L shouldimprove the accuracy of the solution.

Figure 10 shows one common method of creating a non-uniform mesh. Thewidth of adjacent control volumes differs by a constant factor, i.e.

∆xi+1

∆xi= r (28)

where r is a fixed constant. To create such a mesh, one specifies the total lengthL of the region to be subdivided, the stretching ratio r, and the number ofcontrol volumes n. The widths of the control volumes must add up to L, viz.

L =n∑

i=1

∆xi = ∆x1 + r∆x1 + r2∆x1 + . . .+ rn−1∆x1

= ∆x1(1 + r + r2 + . . .+ rn−1

)Define

S = 1 + r + r2 + . . .+ rn−1 =1− rn

1− r(29)

where the second equality is an identity. Thus, L = ∆x1S or

∆x1 =L

S. (30)

To create a mesh with a geometric progression of sizes

1. Specify L, r, and n.

2. Compute ∆x1 from Equation (30).

Page 15: Convection Up Wind

7 SUMMARY 15

10−4

10−3

10−2

10−1

100

10−4

10−3

10−2

10−1

100

101

∆ x

Ma

x e

rro

r

Central

Upwind

Figure 9: Reduction in error as mesh is refined for upwind and central differenceschemes. The plot data is from the ∆x, ||eu||∞, and ||ec||∞ columns in Table 1.

3. Compute the remaining cell widths with a loop.

These calculations are performed by the fvMesh function in Listing 6. ThedemoStretchMesh function uses the fvMesh function to create and plot a one-dimensional with r > 1 and another with r < 1.

The central1D, upwind1D, and compConvect1D functions allow specificationof the mesh stretch ratio r. For example, the following Matlab session com-pares the performance of the central difference and upwind difference schemeon a mesh with 38 control volumes that decrease in size by a factor of 0.95.

>> compConvect1D(40,5,0.1,0.95)

PeL = 50.000 Pex_ave, max(Pex), min(Pex) = 1.316, 2.915, 0.437

Max error = 2.222e-002 for CDS scheme

Max error = 6.476e-002 for UDS scheme

The solutions are plotted in Figure 11. Note that the average cell Pex is less than2, but the maximum Pex is greater than two. This shows that the oscillationsin the central difference solution depend on the gradient of the solution as wellas the local Pex.

7 Summary

The results of computations presented in this paper support the following con-clusions.

• Numerical solutions to Equation (1) obtained with the central differencescheme on a uniform mesh will oscillate if Pex > 2.

Page 16: Convection Up Wind

REFERENCES 16

• Numerical solutions to Equation (1) obtained with the upwind differencescheme never oscillate for any value of Pex.

• The stability provided by the upwind difference scheme is obtained witha loss of accuracy. The upwind difference scheme has a truncation errorthat is O (∆x).

• The truncation error of the central difference scheme is O(∆x2

).

• A non-uniform mesh can be used to reduce or eliminate oscillations in thecomputed solution if the cells with smaller size (closer mesh spacing) isconcentrated in regions with steep gradients in the solutions

The mesh refinement exercise verifies that the central difference scheme isindeed more accurate than the upwind scheme for sufficiently fine meshes. Thisis especially apparent from the plot of errors in Figure 9. The existence ofoscillatory solutions from the central difference scheme is a worry. However,since one goal of most numerical modeling is (or should be) to obtain mesh-independent solutions, the more rapidly convergent central difference scheme ispreferred.

The reader should be aware that there are many more schemes for inter-polation in the convection-diffusion equation. A recent paper by Wang andHutter [6] compares no fewer than twelve methods. In addition to accuracy, onemust be concerned about computational cost for multidimensional problems andnumerical stability.

Ferziger and Peric caution against relying too heavily on performance com-parisons obtained from solving Equation (1). They state [2, §3.11]

Indeed, use of this problem as a test cast has probably producedmore poor choices of method than any other in the field. Despitethese difficulties, we shall consider this problem as some of the issuesit raises are worthy of attention.

The toy codes presented in this paper provide sample implementations ofthe central difference and upwind difference schemes for the one-dimensionaladvection-diffusion equation. Numerical results demonstrate the oscillationsproduced by the central difference scheme on coarse meshes, as well as thesuperior reduction in truncation error obtained by the central difference schemeas the mesh is refined.

References

[1] Michael B. Abbot and D.R. Basco. Computational Fluid Dynamics: AnIntroduction for Engineers. Longman, Essex, UK, 1989.

[2] Joel H. Ferziger and Milovan Peric. Computational Methods for Fluid Dy-namics. Springer-Verlag, Berlin, third edition, 2001.

[3] Joe D. Hoffman. Numerical Methods for Engineers and Scientists. McGraw-Hill, New York, 1992.

[4] S.V. Patankar. Numerical Heat Transfer and Fluid Flow. Hemisphere, Wash-ington D.C., 1980.

Page 17: Convection Up Wind

REFERENCES 17

[5] H.K. Versteeg and W. Malalasekera. An Introduction to Computational FluidDynamics: The Finite Volume Method. Longman, Essex, UK, 1995.

[6] Yongqi Wang and Kolumban Hutter. Comparisons of numerical methodswith respect to convectively dominanted problems. International Journalfor Numerical Methods in Fluids, 37:721–745, 2001.

[7] Pieter Wesseling. Principles of Computational Fluid Dynamics. Springer,Heidelberg, 2001.

Appendix: Code Listings

Table 2: Matlab functions used to implement and test the finite-volume ap-proximation to one-dimensional, convection-diffusion equation.

m-file Description

central1D Evaluate control-volume, finite-difference coefficientsusing the central difference scheme for the convectionterms.

compConvect1D Compare central difference and upwind difference so-lutions to the model problem.

demoConvect1D Solve the model problem with central difference orupwind difference schemes. Compute and print thetruncation error.

demoStretchMesh Create visual representation of stretched meshes.

fvMesh1D Create variables that define a one-dimensional finite-volume mesh. Uniform and stretched meshes can becreated.

refineConvect1D Solve the model problem with central difference orupwind difference schemes on a sequence of finermeshes. Compute and print the truncation error.

upwind1D Evaluate control-volume, finite-difference coefficientsusing the upwind difference scheme for the convec-tion terms.

Page 18: Convection Up Wind

REFERENCES 18

∆x1 ∆x2 ∆x3 ∆xn

L

Figure 10: Non-uniform mesh based on geometric progression of control volumewidths.

0 0.2 0.4 0.6 0.8 1−0.5

0

0.5

1

1.5

2

x

φ

PeL = 50.0, Pe

x = 1.3

||ec|| = 0.022, ||e

u|| = 0.065

Central

Upwind

Exact

Figure 11: Solution of the model problem on a nonuniform mesh with 38 controlvolumes and a stretch ratio of 0.95.

Page 19: Convection Up Wind

REFERENCES 19

function [aw,ap,ae,b] = central1D(u,gam,x,xw,dx,delxw,phib,src)% central1D Central difference coefficients for 1D advection-diffusion equation%% Synopsis: [aw,ap,ae,b] = central1D(u,gam,x,xw,phib)% [aw,ap,ae,b] = central1D(u,gam,x,xw,phib,src)%% Input: u = (scalar) uniform velocity.% gam = (scalar) uniform diffusion coefficient% x = vector of positions of cell centers. There are m-2 interior cells.% xw = vector of positions of west faces of cells.% phib = two-element vector containing boundary values. phib(1) = phi at x=0;% phib(2) = phi at x=xlen% src = (optional) source term. If no value is given, src=0 is assumed. If% src is a scalar (constant), it is replicated as a uniform source term.% Otherwise, src can be a row or column vector with m elements. The i=1% and i=m elements are ignored, as these correspond to boundary nodes.%% Output: aw,ap,ae = coefficients of 3 point central difference scheme% b = right hand side vector% x = vector of locations of cell centers

if nargin<8, src = 0; end % Default: no source term

% --- Compute CVFD coefficientsm = length(x);ae = zeros(m,1); aw = ae;for i=2:m-1

be = 0.5*dx(i)/delxw(i+1);ae(i) = (gam/delxw(i+1) - u*be)/dx(i);bw = 0.5*dx(i)/delxw(i);aw(i) = (gam/delxw(i) + u*bw)/dx(i);

endap = ae + aw; % ap is a vector with same shape as ae and aw

% --- Create right hand side vectorif prod(size(src)) == 1 % src is a scalar ==> replicate for all cells

b = src*ones(m,1);elseif prod(size(src)) == m % src is properly sized

b = src(:); % make sure it’s a column vectorelse

error(sprintf(’size(src) = %d %d is incompatible with mesh definition’,m));end

% --- Apply boundary conditionsap(1) = 1; ae(1) = 0; b(1) = phib(1); % prescribed phi at west boundaryaw(m) = 0; ap(m) = 1; b(m) = phib(2); % prescribed phi at east boundary

Listing 1: The central1d function computes the finite volume coefficients forone-dimensional, convection diffusion equation using central differencing for theconvection term.

Page 20: Convection Up Wind

REFERENCES 20

function demoConvect1D(scheme,m,u,gam,r)% demoConvect1D Test finite volume solution to 1D advection-diffusion equation%% Synopsis: demoConvect1D% demoConvect1D(scheme)% demoConvect1D(scheme,m)% demoConvect1D(scheme,m,u,)% demoConvect1D(scheme,m,u,gam)% demoConvect1D(scheme,m,u,gam,r)%% Input: scheme = (optional,string) indicates convection modeling scheme% scheme = ’UDS’ for upwind differencing% ’CDS’ for central differencing% m = (optional) total number of nodes; Default: m = 12% Internal cell width = 1/(m-2). Domain length is 1% u = (optional, scalar) uniform velocity. Default: u = 5% gam = (optional, scalar) diffusion coefficient; Default: gam = 0.1% r = mesh stretching ratio. If r=1, mesh is uniform% If r>1 control volume widths increase with x. If r<1, control% volume widths decrease with x.%% Output: Plot exact and numerical solutions, print max error in numerical solution

if nargin<1, scheme=’CDS’; endif nargin<2, m = 12; endif nargin<3, u = 5; endif nargin<4, gam = 0.1; endif nargin<5, r = 1; end

% --- Set constants and default input valuesxlen = 1; % domain lengthphib = [1 0]; % boundary values

% --- Create the mesh. fvMesh1D works for uniform or stretched meshes[x,xw,dx,delxw] = fvMesh1D(m-2,xlen,r);

% --- Get CVFD coefficients and solve the systemif strcmp(upper(scheme),’UDS’)

[aw,ap,ae,b] = upwind1D(u,gam,x,xw,dx,delxw,phib);elseif strcmp(upper(scheme),’CDS’)

[aw,ap,ae,b] = central1D(u,gam,x,xw,dx,delxw,phib);else

error(sprintf(’scheme = %s is not supported’,scheme));endphi = tridiagSolve(ap,-ae,-aw,b); % solve the system of equations

% --- Evaluate exact solution and maximum error in the numerical solutionPeL = u*xlen/gam;pe = phib(1) + (phib(2)-phib(1))*(exp(u*x/gam) - 1)/(exp(PeL)-1);maxerr = norm(phi-pe,inf);Pex = u*dx(2:end-1)/gam; Pexave = u*xlen/(m-2)/gam;fprintf(’PeL = %5.3f Pex_ave, max(Pex), min(Pex) = %5.3f, %5.3f, %5.3f\n’,...

PeL,Pexave,max(Pex),min(Pex));fprintf(’\tMax error = %6.4f for %s scheme\n’,maxerr,scheme);

% --- plot resultsxe = linspace(0,xlen); % many x values makes smooth curve for exact solutionpe = phib(1) + (phib(2)-phib(1))*(exp(u*xe/gam) - 1)/(exp(u*xlen/gam)-1);plot(x,phi,’o--’,xe,pe,’-’);legend(sprintf(’%s solution’,scheme),’exact’,2);xlabel(’x’); ylabel(’\phi’,’Rotation’,0); axis([0 xlen min(phib) 1.5*max(phib)])text(0.1,0.4,sprintf(’PeL = %-4.1f, Pex_{ave} = %-4.1f’,PeL,Pexave),’Fontsize’,14);text(0.1,0.25,sprintf(’%s scheme, Max error = %-5.3f’,scheme,maxerr),’Fontsize’,14);

Listing 2: The demoConvect1D function obtains solutions to the one-dimensionalconvection-diffusion equation using either upwind or central differencing for theconvection terms.

Page 21: Convection Up Wind

REFERENCES 21

function [aw,ap,ae,b] = upwind1D(u,gam,x,xw,dx,delxw,phib,src)% upwind1D Upwind difference coefficients for 1D advection-diffusion equation%% Synopsis: [aw,ap,ae,b] = upwind1D(u,gam,x,xw,phib)% [aw,ap,ae,b] = upwind1D(u,gam,x,xw,phib,src)%% Input: u = (scalar) uniform velocity.% gam = (scalar) uniform diffusion coefficient% x = vector of positions of cell centers. There are m-2 interior cells.% xw = vector of positions of west faces of cells.% phib = two-element vector containing boundary values. phib(1) = phi at x=0;% phib(2) = phi at x=xlen% src = (optional) source term. If no value is given, src=0 is assumed. If% src is a scalar (constant), it is replicated as a uniform source term.% Otherwise, src can be a row or column vector with m elements. The i=1% and i=m elements are ignored, as these correspond to boundary nodes.%% Output: aw,ap,ae = coefficients of 3 point upwind difference scheme% b = right hand side vector% x = vector of locations of cell centers

if nargin<8, src = 0; end % Default: no source term

% --- Compute CVFD coefficients% NOTE: For this 1D problem, u is constant, so bw and be are evaluated% once. In general, bw and be vary with position and must be% updated inside the loop that assigns ae(i) and aw(i)m = length(x);ae = zeros(m,1); aw = ae;if u>0

bw = 1; be = 0;else

bw = 0; be = 1;endfor i=2:m-1

ae(i) = (gam/delxw(i+1) - u*be)/dx(i);aw(i) = (gam/delxw(i) + u*bw)/dx(i);

endap = ae + aw; % ap is a vector with same shape as ae and aw

% --- Create right hand side vectorif prod(size(src)) == 1 % src is a scalar ==> replicate for all cells

b = src*ones(m,1);elseif prod(size(src)) == m % src is properly sized

b = src(:); % make sure it’s a column vectorelse

error(sprintf(’size(src) = %d %d is incompatible with mesh definition’,m));end

% --- Apply boundary conditionsap(1) = 1; ae(1) = 0; b(1) = phib(1); % prescribed phi at west boundaryaw(m) = 0; ap(m) = 1; b(m) = phib(2); % prescribed phi at east boundary

Listing 3: The upwind1d function computes the finite volume coefficients forone-dimensional, convection diffusion equation using upwind differencing forthe convection term.

Page 22: Convection Up Wind

REFERENCES 22

function compConvect1D(m,u,gam,r)% compConvect1D Compare CDS and UDS schemes for 1D advection-diffusion equation.% Plot a comparision with exact solution, and print truncation errors.%% Synopsis: compConvect1D% compConvect1D(m)% compConvect1D(m,u)% compConvect1D(m,u,gam)% compConvect1D(m,u,gam,r)%% Input: m = total number of nodes; Number of interior cells is m-2% u = (scalar) uniform velocity.% gam = (scalar) uniform diffusion coefficient% r = mesh stretching ratio. If r=1, mesh is uniform%% Output: Plot of central difference and upwind difference solutions. Print% out of truncation errors

if nargin<1, m = 12; end % mesh sizeif nargin<2, u = 5; endif nargin<3, gam = 0.1; endif nargin<4, r = 1; end

% --- Constantsxlen = 1; % Length of the domainphib = [1 0]; % boundary values

% --- Get CVFD coefficients and solve the system[x,xw,dx,delxw] = fvMesh1D(m-2,xlen,r); % Create the mesh[aw,ap,ae,b] = central1D(u,gam,x,xw,dx,delxw,phib); % Central difference schemephic = tridiagSolve(ap,-ae,-aw,b); % solve the system of equations[aw,ap,ae,b] = upwind1D(u,gam,x,xw,dx,delxw,phib); % Upwind difference schemephiu = tridiagSolve(ap,-ae,-aw,b); % solve the system of equations

% --- Compare with exact solutionPeL = u*xlen/gam;pe = phib(1) + (phib(2)-phib(1))*(exp(u*x/gam) - 1)/(exp(PeL)-1); % Exact solutionerrc = norm(phic-pe,inf); erru = norm(phiu-pe,inf); % Maximum errorsPex = u*dx(2:end-1)/gam; % Local Pe where dx>0Pexave = u*xlen/(m-2)/gam; % Pe based on "average" dxfprintf(’PeL = %5.3f Pex_ave, max(Pex), min(Pex) = %5.3f, %5.3f, %5.3f\n’,...

PeL,Pexave,max(Pex),min(Pex));fprintf(’\tMax error = %11.3e for CDS scheme\n’,errc);fprintf(’\tMax error = %11.3e for UDS scheme\n’,erru);

% --- Plot resultsxe = linspace(0,xlen); % For smooth curve use 100 points independent of mesh sizepe = phib(1) + (phib(2)-phib(1))*(exp(u*xe/gam) - 1)/(exp(PeL)-1);plot(x,phic,’o--’,x,phiu,’*--’,xe,pe,’k-’);xlabel(’x’); ylabel(’\phi’,’Rotation’,0); legend(’Central’,’Upwind’,’Exact’,2);text(0.1,0.5,sprintf(’Pe_L = %-3.1f, Pe_x = %-3.1f’,PeL,Pexave),’Fontsize’,14);text(0.1,0.1,sprintf(’||e_c|| = %5.3f, ||e_u|| = %5.3f’,errc,erru),’Fontsize’,14);axis([0 xlen -0.5 2]);

Listing 4: The compConvect1D function obtains solutions to one-dimensional,convection diffusion equation using both central differencing and upwind differ-encing.

Page 23: Convection Up Wind

REFERENCES 23

function refineConvect1D(mm,u,gam)% refineConvect1D Mesh refinement of solutions to 1D advection-diffusion equation.% Obtain CDS and UDS solutions at different mesh sizes.%% Synopsis: refineConvect1D% refineConvect1D(mm)% refineConvect1D(mm,u)% refineConvect1D(mm,u,gam)%% Input: mm = vector of m values. m is the number of nodes (including boundary% nodes) in the domain. Default: mm = [8 16 32 64 128 256 512].% CDS and UDS solutions are obtained for each m in mm.% u = (optional, scalar) uniform velocity. Default: u = 5% gam = (optional, scalar) diffusion coefficient; Default: gam = 0.1%% Output: Table of truncation errors versus mesh size. Plot of same data.

if nargin<1, mm = [8 16 32 64 128 256 512 1024]; end % Sequence of meshesif nargin<2, u = 5; endif nargin<3, gam = 0.1; end

% --- Constantsxlen = 1; % Length of the domainphib = [1 0]; % boundary valuesPeL = u*xlen/gam;

% --- Loop over mesh sizesfor i = 1:length(mm)

[x,xw,dx,delxw] = fvMesh1D(mm(i)-2,xlen); % Uniform mesh[aw,ap,ae,b] = upwind1D(u,gam,x,xw,dx,delxw,phib); % Get UDS coefficientsphiu = tridiagSolve(ap,-ae,-aw,b); % and solve[aw,ap,ae,b] = central1D(u,gam,x,xw,dx,delxw,phib); % Get CDS coefficientsphic = tridiagSolve(ap,-ae,-aw,b); % and solvepe = phib(1) + (phib(2)-phib(1))*(exp(u*x/gam)-1)/(exp(PeL)-1); % Exact solutionerru(i) = norm(phiu-pe,inf); errc(i) = norm(phic-pe,inf); % Maximum errors

end

% --- Plot error versus mesh dimension, and print same data in a tableDeltax = xlen./(mm-2); % CV sizesloglog(Deltax,errc,’o--’,Deltax,erru,’*--’);xlabel(’\Delta x’); ylabel(’Max error’); legend(’Central’,’Upwind’,2);

fprintf(’\n\nSolution for Pe_L = %f\n’,PeL)fprintf(’\n -- Upwind -- -- Cent. Diff. --\n’);fprintf(’ Max Error Max Error\n’);fprintf(’ m Delta x Pe_x error ratio error ratio\n’);for i=1:length(errc)

fprintf(’%5d %9.6f %6.2f %8.5f’,mm(i),Deltax(i),Deltax(i)*u/gam,erru(i));if i>1

fprintf(’ %7.2f %8.5f %7.2f\n’,erru(i-1)/erru(i),errc(i),errc(i-1)/errc(i));else

fprintf(’ %8.5f\n’,errc(i));end

end

Listing 5: The refineConvect1D function demonstrates the reduction of trun-cation error with mesh size for numerical solutions to the one-dimensional,convection diffusion equation. Numerical solutions are obtained with centraldifferencing and upwind differencing.

Page 24: Convection Up Wind

REFERENCES 24

function [x,xw,dx,delxw] = fvMesh1D(nx,xlen,r)% fvMesh1D Create one-dimensional finite-volume mesh. Uniform meshes and% stretched non-uniform meshes are supported.%% Synopsis: [x,xw] = fvMesh1D% [x,xw] = fvMesh1D(nx)% [x,xw] = fvMesh1D(nx,xlen)% [x,xw] = fvMesh1D(nx,xlen,r)% [x,xw,dx] = fvMesh1D(...)% [x,xw,dx,delxw] = fvMesh1D(...)%% Input: nx = Number of cells (internal CVs, not nodes). Default: nx=10% xlen = overall length of the mesh. Default: xlen = 1% r = growth ratio: dx(i+1) = r*dx(i). Default: r = 1, i.e mesh% is uniform. If r>1 control volume widths increase with x.% If r<1, control volume widths decrease with x.%% Output: x = vector of node locations, including nodes on the boundaries% xw = vector of interface locations on east of each node% xw(1) = xw(2) = 0, xw(nx+2) = xlen% dx = vector of CV widths: dx(i) = xw(i+1)-xw(i)% delxw = vector of x(i) - x(i-1); dx(1)=0

if nargin<1, nx = 10; endif nargin<2, xlen = 1; endif nargin<3, r = 1; end

% --- Create a mesh where dx(i+1) = r*dx(i)if abs(r-1)<10*eps;

s = nx; % Mesh is uniform, limit as s->1 is n; avoid 1/0else

s = (1-r^nx)/(1-r); % Normal formula for stretched meshenddx = xlen/s; % Width of smallest control volumexw = zeros(nx+2,1);for i=3:nx+2

xw(i) = xw(i-1) + dx;dx = dx*r;

end

% --- Now that control volumes are defined, locate nodes in the centroidsx = zeros(size(xw));for i=2:nx+1

x(i) = (xw(i)+xw(i+1))/2;endx(nx+2) = xlen;

% --- Compute vectors of control volume widthsif nargout>2, dx = [ diff(xw); 0]; end % CV widths: dx(i) = xw(i+1) - xw(i)if nargout>3, delxw = [0; diff(x)]; end % node spacing: delxw(i) = x(i) - x(i-1)

Listing 6: Utility program to create a one-dimensional finite-volume mesh withm− 2 control volumes and m nodes.