47: s=linspace0,sk,1+sk*nseg’;48: Zk=spline0:sk,zk,s; Z=[Z;Zk2:end]; 49: end 50: X=realZ; Y=imagZ; 4.3 Numerical Differentiation Using Finite Differences Differential equation problems a
Trang 12: %
3: % [area,leng,X,Y,closed]=curvprop(x,y,doplot)
4: % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5: % This function passes a cubic spline curve through
6: % a set of data values and computes the enclosed
7: % area, the curve length, and a set of points on
8: % the curve
9: %
10: % x,y - data vectors defining the curve
11: % doplot - plot the curve if a value is input for
13: % area - the enclosed area is computed This
21: % leng - length of the curve
22: % X,Y - set of points on the curve The output
25: % closed - equals one for a closed curve Equals zero
Trang 247: closed=0; endc=1; zp=spterp(t,z,1,t,endc);
57: plot(X,Y,’-’,x,y,’.’), axis equal
58: xlabel(’x axis’), ylabel(’y axis’)
69: % This function performs cubic spline
interpo-70: % lation Values of y(x),y’(x),y’’(x) or the
71: % integral(y(t)*dt, xd(1) x) are obtained
72: % Five types of end conditions are provided
79: % v - values of the function, first
86: % endv - vector giving the end conditions in
Trang 392: % values at each end
128: % This function determines spline interpolation
129: % coefficients consisting of the support
130: % reactions concatenated with y’ and y’’ at
131: % the left end
132: % x,y - data vectors of interplation points
134: % endv - vector of data for end conditions
136: %
Trang 4137: % c - a vector [c(1); ;c(n+2)] where the
141:
142: if nargin<3, endv=1; end
143: x=x(:); y=y(:); n=length(x); u=x(2:n)-x(1);
153: elseif endv(1)==3 % Slope, force condition
154: b(n+1)=endv(2); a(n+1,n+1)=1; a(n+2,n-1)=1;
155: elseif endv(1)==4 % Force, slope condition
166: if endv(1)==1 & n<4, c=pinv(a)*b;
167: else, c=a\b; end
175: % This function evaluates various powers of a
176: % matrix used in cubic spline interpolation
177: %
178: % x,X - arbitrary vectors of length n and N
179: % a - an n by M matrix of elements such that
180: % a(i,j)=(x(i)>X(j))*abs(x(i)-X(j))^p
181:
Trang 5182: x=x(:); n=length(x); X=X(:)’; N=length(X);
183: a=x(:,ones(1,N))-X(ones(n,1),:); a=a.*(a>0);
184: switch p, case 0, a=sign(a); case 1, return;
185: case 2, a=a.*a; case 3; a=a.*a.*a;
186: case 4, a=a.*a; a=a.*a; otherwise, a=a.^p; end
4.2.3 Generalizing the Intrinsic Spline Function in MATLAB
The intrinsic MATLAB function spline employs an auxiliary function unmk to
create the piecewise polynomial deÞnitions deÞning the spline The polynomials
can be differentiated or integrated, and then functions mkpp and ppval can be used
to evaluate results We have employed the ideas from those routines to develop
func-tions splineg and splincof extending the minimal spline capabilities of MATLAB The function splincof(xd,yd,endc) computes arrays b and c usable by mkpp and pp- val The data vector endc deÞnes the Þrst four types of end conditions discussed above The function splineg(xd,yd,x,deriv,endc,b,c) handles the same kind of data
as function spterp Sometimes arrays b and c may have been created from a ous call to splineg or spterp Whenever these are passed through the call list, they are used by splineg without recomputation Readers wanting more details on spline
previ-concepts should consult de Boor’s book [7].
Two examples illustrating spline interpolation are presented next In the Þrst
pro-gram called, sinetrp, a series of equally spaced points between 0 and 2π is used to
approximate y = sin(x) which satisÞes
y (x) = cos(x) , y (x) = − sin(x) ,
x
0
y(x)dx = 1 − cos(x).
The approximations for the function, derivatives, and the integral are evaluated using
splineg Results shown inFigure 4.1 are quite satisfactory, except for points outside
the data interval [0, 2π].
Trang 6∫ y(x) dx
Figure 4.1: Spline Differentiation and Integration of sin(x)
Trang 7Example: Spline Interpolation Applied to Sin(x)
Program sinetrp
1: function sinetrp
2: % Example: sinetrp
3: % ~~~~~~~~~~~~~~~~~
4: % This example illustrates cubic spline
5: % approximation of sin(x), its first two
6: % derivatives, and its integral
Trang 841: % For a cubic spline curve through data points
42: % xd,yd, this function evaluates y(x), y’(x),
43: % y’’(x), or integral(y(x)*dx, xd(1) to x(j) )
44: % for j=1:length(x).The coefficients needed to
45: % evaluate the spline are also computed
46: %
47: % xd,yd - data vectors defining the cubic
51: % deriv - denoting the spline curve as y(x),
58: % endc - endc=1 makes y’’’(x) continuous at
76: if nargin<5 | isempty(endc), endc=1; end
77: if nargin<7, [b,c]=splincof(xd,yd,endc); end
Trang 9108: % This function determines coefficients for
109: % cubic spline interpolation allowing four
110: % different types of end conditions
111: % xd,yd - data vectors for the interpolation
112: % endc - endc=1 makes y’’’(x) continuous at
Trang 104.2.4 Example: A Spline Curve with Several Parts and Corners
The Þnal spline example illustrates interpolation of a two-dimensional curve where
y cannot be expressed as a single valued function of x Then we introduce a eter t j having its value equal to the index for each (x j , y j) used Interpolating
param-x(t) and y(t) as continuous functions of t produces a smooth curve through the data.
Function matlbdat creates data points to deÞne the curve and calls function spcry2d
to compute points on a general plane curve We also introduce the idea of ‘corner points’ where slope discontinuity allows the curve to make sharp turns needed to describe letters such as the ‘t’ in MATLAB Each curve segment between successive
pairs of corner points is parameterized using function spline Results inFigure 4.2
show clearly that spline interpolation can represent a complicated curve The lated code appears after the Þgure The same kind of parameterization used for two dimensions also works well for three dimensional curves.
re-Example: Spline Curve Drawing the Word MATLAB
Program matlbdat
1: function matlbdat
Trang 11A Spline Curve Drawing the Word MATLAB
Figure 4.2: Spline Curve Drawing the Word MATLAB
Trang 122: % Example: matlbdat
3: % ~~~~~~~~~~~~~~~~~
4: % This example illustrates the use of splines
5: % to draw the word MATLAB
22: plot(xs,ys,’k-’,x,y,’k*’), axis off;
23: title(’A Spline Curve Drawing the Word MATLAB’);
33: % This function computes points (X,Y) on a
34: % spline curve through (xd,yd) allowing slope
35: % discontinuities at points with corner
36: % indices in icrnr nseg plot segments are
37: % used between each successive pair of points
38:
39: if nargin<4, icrnr=[]; end
40: if nargin<3, nseg=10; end
Trang 1347: s=linspace(0,sk,1+sk*nseg)’;
48: Zk=spline(0:sk,zk,s); Z=[Z;Zk(2:end)];
49: end
50: X=real(Z); Y=imag(Z);
4.3 Numerical Differentiation Using Finite Differences
Differential equation problems are sometimes solved using difference formulas to approximate the derivatives in terms of function values at adjacent points Deriving difference formulas by hand can be tedious, particularly when unequal point spacing
is used For this reason, we develop a numerical procedure to construct formulas
of arbitrary order and arbitrary truncation error Of course, as the desired order
of derivative and the order of truncation error increases, more points are needed to interpolate the derivative We will show below that approximating a derivative of
order k with a truncation error of order h m generally requires (k + m) points unless
symmetric central differences are used Consider the Taylor series expansion
where F (k) (x) means the k’th derivative of F (x) This relation expresses values of
F as linear combinations of the function derivatives at x Conversely, the derivative
values can be cast in terms of function values by solving a system of simultaneous equations Let us take a series of points deÞned by
x ı = x + hα ı , 1 ≤ ı ≤ n where h is a Þxed step-size and α ıare arbitrary parameters Separating some leading terms in the series expansion gives
F (x ı) =
n−1
k=0
α k ı k!
h k F (k) (x)
+α
n ı
h (n+1) F (n+1) (x)
+O(h n+2 ) , 1 ≤ ı ≤ n.
It is helpful to use the following notation:
α k – a column vector with component ı being equal to α k
ı
f – a column vector with component ı being F (x ı)
f p – a column vector with component ı being h ı F (ı) (x)
A – [α0, α1, , α n−1], a square matrix with columns which
are powers of α.
Trang 14Then the Taylor series expressed in matrix form is
In the last equation we have retained the Þrst two remainder terms in explicit form
to allow the magnitudes of these terms to be examined Row k + 1 of the previous
(n+1) (x)(A −1 α n+1)k+1+O(h n−k+1 )
Consequently, the rows of A −1provide coefÞcients in formulas to interpolate
deriva-tives For a particular number of interpolation points, say N, the highest derivative approximated will be F (N−1) (x)and the truncation error will normally be of or-
der h1 Conversely, if we need to compute a derivative formula of order k with the truncation error being m, then it is necessary to use a number of points such that
n − k = m; therefore n = m + k For the case where interpolation points are
sym-metrically placed around the point where derivatives are desired, one higher power
of accuracy order is achieved than might be expected We can show, for example, that
d4F (x)
dx4 =
1
h4(F (x − 2h) − 4F (x − h) + 6F (x) − 4F (x + h) + F (x + 2h)) + O(h2)
because the truncation error term associated with h1 is found to be zero At the
same time, we can show that a forward difference formula for f (x)employing equidistant point spacing is
d3F (x)
dx3 =
1
h3(−2.5F (x) − 9F (x + h) + 12F (x + 2h) + 7F (x + 3h) − 1.5F (x + 4h)) + O(h2).
Although the last two formulas contain arithmetically simple interpolation cients, due to equal point spacing, the method is certainly not restricted to equal
coefÞ-spacing The following program contains the function derivtrp which implements
the ideas just developed Since the program contains documentation that is output when it is executed, no additional example problem is included.
Trang 154.3.1 Example: Program to Derive Difference Formulas Output from Example
finitdif;
COMPUTING F(x,k), THE K’TH DERIVATIVE OF
f(x), BY FINITE DIFFERENCE APPROXIMATION
Input the derivative order (give 0 to stop,
or ? for an explanation) > ?
Let f(x) have its k’th derivative denoted by
F(k,x) The finite difference formula for a
stepsize h is given by:
F(x,k)=Sum(c(j)*f(x+a(j)*h), j=1:n)/hˆk +
TruncationError
with m=n-k being the order of truncation
error which decreases like hˆm according to:
TruncationError=-(hˆm)*(e(1)*F(x,n)+
e(2)*F(x,n+1)*h+e(3)*F(x,n+2)*hˆ2+O(hˆ3))
Input the derivative order (give 0 to stop,
or ? for an explanation) > 4
Give the required truncation order > 1
To define interpolation points X(j)=x+h*a(j), input at least 5 components for vector a.
Trang 16or ? for an explanation) > 3
Give the required truncation order > 2
To define interpolation points X(j)=x+h*a(j),
input at least 5 components for vector a.
5: % This program computes finite difference formulas of
6: % general order For explanation of the input and
7: % output parameters, see the following function
8: % findifco When the program is executed without input
9: % arguments, then input is read interactively
10:
11: if nargin==0, disp(’ ’) % Use interactive input
12: disp(’COMPUTING F(x,k), THE K’’TH DERIVATIVE OF’)
13: disp(’f(x), BY FINITE DIFFERENCE APPROXIMATION’)
14: disp(’ ’)
15: while 1
16: disp(’Input the derivative order (give 0 to stop,’)
17: K=input(’or ? for an explanation) > ’,’s’);
19: if strcmp(K,’’) | strcmp(K,’0’); disp(’ ’),return
Trang 1720: elseif strcmp(K,’?’)
39: m=input(’Give the required truncation order > ’);
44: disp(’ ’), aa=input(’Components of a > ’,’s’);
Trang 1865: %
66: % [c,e,m,crat]=findifco(k,a)
67: % ~~~~~~~~~~~~~~~~~~~~~~~~~
68: % This function approximates the k’th derivative
69: % of a function using function values at n
70: % interpolation points Let f(x) be a general
71: % function having its k’th derivative denoted
72: % by F(x,k) The finite difference approximation
73: % for the k’th derivative employing a stepsize h
74: % is given by:
75: % F(x,k)=Sum(c(j)*f(x+a(j)*h), j=1:n)/h^k +
77: % with m=n-k being the order of truncation
78: % error which decreases like h^m and
79: % TruncationError=(h^m)*(e(1)*F(x,n)+
80: % e(2)*F(x,n+1)*h+e(3)*F(x,n+2)*h^2+O(h^3))
81: %
82: % a - a vector of length n defining the
85: % k - order of derivative evaluated at x
86: % c - the weighting coeffients in the
89: % e - error component vector in the above
91: % m - order of truncation order in the
93: % crat - a matrix of integers such that c is
95:
96: a=a(:); n=length(a); m=n-k; mat=ones(n,n+4);
97: for j=2:n+4; mat(:,j)=a/(j-1).*mat(:,j-1); end
98: A=pinv(mat(:,1:n)); ec=-A*mat(:,n+1:n+4);
99: c=A(k+1,:); e=-ec(k+1,:);
100: [ctop,cbot]=rat(c,1e-8); crat=[ctop(:)’;cbot(:)’];
Trang 19Let us assume that an integral over limits a to b is to be evaluated We can write
where E represents the error due to replacement of the integral by a Þnite sum This
is called an n-point quadrature formula The points x ıwhere the integrand is
evalu-ated are the base points and the constants W ıare the weight factors Most integration formulas depend on approximating the integrand by a polynomial Consequently, they give exact results when the integrand is a polynomial of sufÞciently low order.
Different choices of x ı and W ıwill be discussed below.
It is helpful to express an integral over general limits in terms of some Þxed limits, say−1 to 1 This is accomplished by introducing a linear change of variables
integral on the integration limits can be represented parametrically by modifying the
Trang 20integrand Consequently, if an integration formula is known for limits−1 to 1, we
The idea of shifting integration limits can be exploited further by dividing the interval
a to b into several parts and using the same numerical integration formula to evaluate the contribution from each interval Employing m intervals of length = (b −a)/m,
Applying the same n-point quadrature formula in each of m equal intervals gives
what is termed a composite formula
1
−1
f (x)dx = f ( −1) + f(1) + E.
A much more accurate formula results by using a cubic approximation matching the
integrand at x = −1, 0, 1 Let us write
f (x) = c1+ c2x + c3x2+ c
4x3.
Trang 21Then 1
−1
f (x)dx = 2c1 +2
3c3 Evidently the linear and cubic terms do not inßuence the integral value Also, c1 =
The error E in this formula is zero when the integrand is any polynomial of order 3
or lower Expressed in terms of more general limits, this result is
Analyzing the integration error for a particular choice of integrand and quadrature formula can be complex In practice, the usual procedure taken is to apply a com-
posite formula with m chosen large enough so the integration error is expected to
be negligibly small The value for m is then increased until no further signiÞcant
change in the integral approximation results Although this procedure involves some risk of error, adequate results can be obtained in most practical situations.
In the subsequent discussions the integration error that results by replacing an integral by a weighted sum of integrand values will be neglected It must nevertheless
be kept in mind that this error depends on the base points, weight factors, and the particular integrand Most importantly, the error typically decreases as the number
of function values is increased.
It is convenient to summarize the composite formulas obtained by employing a
piecewise linear or piecewise cubic integrand approximation Using m intervals and letting = (b − a)/m, it is easy to obtain the composite trapezoidal formula which
This formula assumes that the integrand is satisfactorily approximated by piecewise
linear functions The MATLAB function trapz implements the trapezoidal rule.
A similar but much more accurate result is obtained for the composite integration
formula based on cubic approximation For this case, taking m intervals implies 2m + 1 function evaluations If we let g = (b − a)/(2m) and h = 2g, then
.
Trang 22This formula, known as the composite Simpson rule, is one of the most commonly
used numerical integration methods The following function simpson works for an
analytically deÞned function or a function deÞned by spline interpolating through discrete data.
Function for Composite Simpson Rule
1: function area=simpson(funcname,a,b,n,varargin)
2: %
3: % area=simpson(funcname,a,b,n,varargin)
4: %
-5: % Simpson’s rule integration for a general function
6: % defined analytically or by a data array
7: %
8: % funcname - either the name of a function valid
19: % varargin - variable number of arguments passed
21: % area - value of the integral when the integrand
Trang 2336: 4*sum(y(2:2:n))+2*sum(y(3:2:n)));
An important goal in numerical integration is to achieve accurate results with only
a few function evaluations It was shown for Simpson’s rule that three function evaluations are enough to exactly integrate a cubic polynomial By choosing the base point locations properly, a much higher accuracy can be achieved for a given number of function evaluations than would be obtained by using evenly spaced base points Results from orthogonal function theory lead to the following conclusions If the base points are located at the zeros of the Legendre polynomials (all these zeros are between−1 and 1) and the weight factors are computed as certain functions of
the base points, then the formula
is exact for a polynomial integrand of degree 2n − 1 Although the theory proving
this property is not elementary, the Þnal results are quite simple The base points and weight factors for a particular order can be computed once and used repeatedly Formulas that use the Legendre polynomial roots as base points are called Gauss quadrature formulas In a typical application, Gauss integration gives much more accurate results than Simpson’s rule for an equivalent number of function evalua- tions Since it is equally easy to use, the Gauss formula is preferable to Simpson’s rule.
MATLAB also has three functions quad and quad8 and quadl to numerically
integrate by adaptive methods These functions repeatedly modify approximations for an integral until the estimated error becomes smaller than a speciÞed tolerance.
In the current text, the function quadl is preferable over the other two functions, and quadl is always used when an adaptive quadrature function is needed Readers should study carefully the system documentation for quadl to understand the various
combinations of call list parameters allowed.
5.2 Concepts of Gauss Integration
This section summarizes properties of Gauss integration which, for the same ber of function evaluations, are typically much more accurate than comparable Newton- Cotes formulas It can be shown for Gauss integration [20] that
Trang 24Integration Error = C*diff( f(x), x, 2*n ) for some x in [−1,1]
Figure 5.1: Error CoefÞcient versus Number of Points for Gauss Integration
where the integration error term is
poly-or lower The coefÞcient of the derivative term in E decreases very rapidly with increasing n, as can be seen in Figure 5.1.
For example, n = 10 gives a coefÞcient of 2.03 × 10 −21 Thus, a function having well behaved high order derivatives can be integrated accurately with a formula of
fairly low order The base points x are all distinct, lie between−1 and 1, and are
the eigenvalues of a symmetric tridiagonal matrix [26] which can be analyzed very
rapidly with the function eigen Furthermore, the weight factors are simply twice
the squares of the Þrst components of the orthonormalized eigenvectors Because
eigen returns orthonormalized eigenvectors for symmetric matrices, only lines 58-60
in function gcquad given below are needed to compute the base points and weight
factors.
Trang 25Function for Composite Gauss Integration
9: % This function integrates a general function using
10: % a composite Gauss formula of arbitrary order The
11: % integral value is returned along with base points
12: % and weight factors obtained by an eigenvalue based
13: % method The integration interval is divided into
14: % mparts subintervals of equal length and integration
15: % over each part is performed with a Gauss formula
16: % making nquad function evaluations Results are
17: % exact for polynomials of degree up to 2*nquad-1
18: % ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
26: % xlow,xhigh - integration limits
30: % varargin - variable length parameter used to
Trang 2642: % gives value = 1.935685556078172e+040 which is
43: % accurate within an error of 1.9e-13 percent
44: %
45: % User m functions called: the function name passed
47:
48:
% -49:
50: if isempty(nquad), nquad=10; end
51: if isempty(mparts), mparts=1; end
52:
53: % Compute base points and weight factors
54: % for the single interval [-1,1] (Ref:
55: % ’Methods of Numerical Integration’ by
56: % P Davis and P Rabinowitz, page 93)
62: % Modify the base points and weight factors
63: % to apply for a composite interval
A program was written to compare the performance of the Gauss quadrature
func-tion gcquad and the numerical integrator quadl provided in MATLAB Quadl is a
robust adaptive integration routine which efÞciently handles most integrands It can
even deal with special integrals having singularities, like log(x) or 1/ sqrt(x) at the
origin Integrating these functions from zero to one yields correct answers although messages occur warning about integrand singularities at the origin No capabilities
Trang 27are provided in quadl to directly handle vector integrands (except one component at a
time), and no options are provided to suppress unwanted warning or error messages.
In the timing program given below, warning messages from quadl were temporarily
turned off for the tests.
Often there are examples involving vector-valued integrands that are to be grated many times over Þxed integration limits A typical case is evaluation of coef- Þcients in Fourier-Bessel series expansions Then, computing a set of base points and weight factors once and using these coefÞcients repeatedly is helpful To illustrate this kind of situation, let us numerically integrate the vector valued function
inte-f (x) = [ √
x ; log(x) ; humps(x); exp(10x) cos(10πx) ; cos(20πx − 20 sin(πx))] from x = 0 to x = 1 Several components of this function are hard to integrate
numerically because √
x has inÞnite slope at x = 0, log(x) is singular at x = 0,
the fourth component is highly oscillatory with large magnitude variations, and the last component is highly oscillatory (integrating the last component gives the value
of the integer order Bessel function J20(20)).
The following function quadtest uses functions quadl and gcquad to integrate
f (x) from x = 0 to x = 1 The Gauss integration employs a formula of order
100 with one subinterval, so integrands are effectively approximated by polynomials
of order 199 To achieve accurate timing, it was necessary to evaluate the integrals repeatedly until a chosen number of seconds elapsed Then average times were com-
puted The program output shows that gcquad was more accurate than quadl for all
cases except for log(x) involving a singular integrand Computations times shown
for each component of f(x) are the same when gcquad was used because the
inte-gration was done for all components at once, and then results were divided by Þve.
The total time used by quadl was about 3.5 times as large as the time for qcquad.
We are not arguing that these results show gcquad is superior to quadl However, it
does imply that Gauss integration can be attractive in some instances The geometry problems in the remainder of this chapter include boundary curves deÞned by cu- bic splines Then, using Gauss integration of sufÞciently high order produces exact results for the desired geometrical properties.
Output from Program quadtest
>> quadtest(10);
PRESS RETURN TO BEGIN COMPUTATION > ?
INTEGRATION TEST COMPARING FUNCTIONS QUADL AND GCQUAD The functions being integrated are:
Trang 28Results Using Function quadl
Results Using Function gcquad
(Total time using quadl)/(Total time using gcquad) equals 3.5395
5: % This program compares the accuracy and
6: % computation times for several integrals
7: % evaluated using quadl and gcquad
8: %
9: % secs - the number of seconds each integration
12: % L,G - matrices with columns containing
17: % names - character matrix with rows
Trang 2919: % which were integrated
35: fprintf([’\n\nINTEGRATION TEST COMPARING’,
37: fprintf(’\nThe functions being integrated are:\n’)
45: % Find time to make a loop and call the clock
46: nmax=5000; nclock=0; t0=clock;
52: % Evaluate each integral individually Repeat
53: % the integrations for secs seconds to get
54: % accurate timing Save results in array L
55: L=zeros(5,4); tol=1e-6; e=exact; warning off;
Trang 3064: end
65: warning on;
66:
67: % Obtain time to compute base points and weight
68: % factors for a Gauss formula of order 100
75: % Perform the Gauss integration using a
76: % vector integrand Save results in array G
101: disp([’(Total time using quadl)/’,