Docsity

Numerical Method: Computer Implementation of Algorithms | MATH 464, Study notes of Mathematical Methods for Numerical Analysis and Optimization

Partial preview of the text

Download Numerical Method: Computer Implementation of Algorithms | MATH 464 and more Study notes Mathematical Methods for Numerical Analysis and Optimization in PDF only on Docsity!

Numerical Methods: Design, Analysis, and Computer

Implementation of Algorithms

Anne Greenbaum^1 Timothy P. Chartier

September 27, 2007

(^1) These are course notes for Math 464/5/6, given Autumn 2006 through Spring 2007 at the University

of Washington by Anne Greenbaum. Professor Greenbaum and Professor Chartier retain the copyright to these notes. They do not give anyone permission to copy computer files related to them. Send email to [email protected].

Contents

  • 1 Basic Operations with MATLAB
    • 1.1 Launching MATLAB
    • 1.2 Vectors
    • 1.3 Getting help
    • 1.4 Matrices
    • 1.5 Creating and running .m files
    • 1.6 Comments
    • 1.7 Plotting
    • 1.8 Creating your own functions
    • 1.9 Printing
    • 1.10 More loops and conditionals
    • 1.11 Clearing variables
    • 1.12 Logging your session
    • 1.13 More advanced commands
  • 2 Solution of a Single Nonlinear Equation in One Unknown
    • 2.1 Bisection
    • 2.2 Taylor’s Theorem
    • 2.3 Newton’s Method
    • 2.4 Quasi-Newton Methods
      • 2.4.1 Avoiding Derivatives
      • 2.4.2 Constant Slope Method
      • 2.4.3 Secant Method
    • 2.5 Analysis of Fixed Point Methods
    • 2.6 Fractals, Julia Sets and Mandelbrot Sets*
  • 3 Floating Point Arithmetic
    • 3.1 Costly Disasters Caused by Rounding Errors
    • 3.2 Binary Representation and Base 2 Arithmetic
    • 3.3 Floating Point Representation
    • 3.4 IEEE Floating Point Arithmetic
    • 3.5 Rounding
    • 3.6 Correctly Rounded Floating Point Operations
    • 3.7 Exceptions
  • 4 Conditioning of Problems; Stability of Algorithms
    • 4.1 Conditioning of Problems
    • 4.2 Stability of Algorithms
  • 5 Solving Linear Systems and Least Squares Problems
    • 5.1 Review of Matrix Algebra
    • 5.2 Gaussian Elimination
      • 5.2.1 Operation Counts
      • 5.2.2 LU Factorization
      • 5.2.3 Pivoting
      • 5.2.4 Banded Matrices and Matrices for which Pivoting is Not Required
      • 5.2.5 Implementation Considerations for High Performance*
    • 5.3 Other Methods for Solving Ax = b
    • 5.4 Conditioning of Linear Systems
      • 5.4.1 Norms
      • 5.4.2 Sensitivity of Solutions of Linear Systems
    • 5.5 Stability of Gaussian Elimination with Partial Pivoting
    • 5.6 Least Squares Problems
      • 5.6.1 The Normal Equations
      • 5.6.2 QR Decomposition
      • 5.6.3 Fitting Polynomials to Data
  • 6 Polynomial and Piecewise Polynomial Interpolation
    • 6.1 The Vandermonde System
    • 6.2 The Lagrange Form of the Interpolation Polynomial
    • 6.3 The Newton Form of the Interpolation Polynomial
      • 6.3.1 Divided Differences
    • 6.4 The Error in Polynomial Interpolation
    • 6.5 Piecewise Polynomial Interpolation
      • 6.5.1 Piecewise Cubic Hermite Interpolation
      • 6.5.2 Cubic Spline Interpolation
  • 7 Numerical Differentiation and Richardson Extrapolation
    • 7.1 Numerical Differentiation
    • 7.2 Richardson Extrapolation
  • 8 Numerical Integration
    • 8.1 Newton-Cotes Formulas
    • 8.2 Formulas Based on Piecewise Polynomial Interpolation
    • 8.3 Gaussian Quadrature
      • 8.3.1 Orthogonal Polynomials
    • 8.4 Romberg Integration
    • 8.5 Periodic Functions and the Euler-Maclaurin Formula
    • 8.6 Singularities
    • tions 9 Numerical Solution of the Initial Value Problem for Ordinary Differential Equa-
    • 9.1 Existence and Uniqueness of Solutions
    • 9.2 One-Step Methods
      • 9.2.1 Euler’s Method
      • 9.2.2 Higher Order Methods Based on Taylor Series
      • 9.2.3 Midpoint Method
      • 9.2.4 Methods Based on Quadrature Formulas
      • 9.2.5 Classical Fourth-Order Runge-Kutta and Runge-Kutta-Fehlberg Methods.
      • 9.2.6 Analysis of One-Step Methods
      • 9.2.7 Practical Implementation Considerations
      • 9.2.8 Systems of Equations
    • 9.3 Multistep Methods
      • 9.3.1 Adams-Bashforth and Adams-Moulton Methods
      • 9.3.2 General m-Step Methods
      • 9.3.3 Linear Difference Equations
      • 9.3.4 The Dahlquist Equivalence Theorem
    • 9.4 Stiff Equations
      • 9.4.1 Absolute Stability
      • 9.4.2 Backward Differentiation Formulae (BDF Methods)
      • 9.4.3 Implicit Runge-Kutta (IRK) Methods
    • 9.5 Solving Systems of Nonlinear Equations in Implicit Methods
      • 9.5.1 Fixed Point Iteration
      • 9.5.2 Newton’s Method
    • Methods for Solving Linear Systems 10 More Numerical Linear Algebra: Eigenvalues, Singular Values, and Iterative
    • 10.1 Eigenvalue Problems
      • 10.1.1 The Power Method for Computing the Largest Eigenpair
      • 10.1.2 Inverse Iteration
      • 10.1.3 Rayleigh Quotient Iteration
      • 10.1.4 The QR Algorithm
      • 10.1.5 Google’s PageRank
  • 11 Numerical Solution of Two-Point Boundary Value Problems
    • 11.1 An Application: Steady-State Temperature Distribution
    • 11.2 Finite Difference Methods
      • 11.2.1 Accuracy
      • 11.2.2 More General Equations and Boundary Conditions
    • 11.3 Finite Element Methods
      • 11.3.1 Accuracy
  • 12 Numerical Solution of Partial Differential Equations
    • 12.1 Elliptic Equations
      • 12.1.1 Finite Difference Methods
      • 12.1.2 Finite Element Methods
    • 12.2 Parabolic Equations
      • 12.2.1 Semidiscretization and the Method of Lines
      • 12.2.2 Discretization in Time
    • 12.3 Separation of Variables
      • 12.3.1 Separation of Variables for Difference Equations
    • 12.4 Hyperbolic Equations
      • 12.4.1 Characteristics
      • 12.4.2 Systems of Hyperbolic Equations
      • 12.4.3 Boundary Conditions
      • 12.4.4 Finite Difference Methods
    • 12.5 Fast Methods for Poisson’s Equation
      • 12.5.1 The Fast Fourier Transform
    • 12.6 Multigrid Methods

are described in programs throughout the book. For further information about using MATLAB, we recommend [11].

1.1 Launching MATLAB

MATLAB is a high level programming language that is especially well-suited to linear algebra type computations, but it can be used for almost any numerical problem. Following are some of the basic features of MATLAB that you will need to carry out the programming exercises in this book. Depending on what system you are using, you will start MATLAB either by double clicking on a MATLAB icon or by typing ‘matlab’ or by some similar means. When MATLAB is ready for input from you it will give a prompt such as >>. You can use MATLAB like a calculator. For instance, if you type at the prompt:

>> 1+2*

then MATLAB returns with the answer:

ans =

7

Since you did not give a name to your result, MATLAB stores the result in a variable called ‘ans’. You can do further arithmetic using the result in ‘ans’:

>> ans/

and MATLAB will return with the result:

ans =

1.2 Vectors

MATLAB can store row or column vectors. The following commands:

>> v = [1; 2; 3; 4]

v =

1 2 3 4

>> w = [5, 6, 7, 8]

w =

5 6 7 8

create a column vector v of length 4 and a row vector w of length 4. In general, when defining a matrix or vector, semicolons are used to separate rows, while commas or spaces are used to separate the entries within a row. You can refer to an entry of a vector by giving its index:

>> v(2)

ans =

2

>> w(3)

ans =

7

MATLAB can add two vectors of the same dimension, but it cannot add v and w because v is 4 × 1 and w is 1 × 4. If you try to do this, MATLAB will give an error message:

>> v+w ??? Error using ==> + Matrix dimensions must agree.

The transpose of w is denoted w’:

>> w’

ans =

5 6 7 8

You can add v and w’ using ordinary vector addition:

>> v + w’

ans =

1.3 Getting help

Actually, the entries of a vector are most easily summed using a builtin MATLAB function called sum. If you are unsure of how to use a MATLAB function or command, you can always type: help followed by the command name, and MATLAB will provide an explanation of how the command works:

>> help sum

SUM Sum of elements. For vectors, SUM(X) is the sum of the elements of X. For matrices, SUM(X) is a row vector with the sum over each column. For N-D arrays, SUM(X) operates along the first non-singleton dimension.

SUM(X,DIM) sums along the dimension DIM.

Example: If X = [0 1 2 3 4 5]

then sum(X,1) is [3 5 7] and sum(X,2) is [ 3 12];

See also PROD, CUMSUM, DIFF.

In general, you can type help in MATLAB and receive a summary of the classes of commands for which help is available. If you are not sure of the command name for which you are looking, there are two other helpful commands. First, typing helpdesk displays the help browser, which is a very helpful tool. Second, if you are interested in commands related to summing, you can type lookfor sum. With this command, MATLAB searches for the specified keyword “sum” in all help entries. This command results in the following:

>> lookfor sum TRACE Sum of diagonal elements. CUMSUM Cumulative sum of elements. SUM Sum of elements. SUMMER Shades of green and yellow colormap. UIRESUME Resume execution of blocked M-file. UIWAIT Block execution and wait for resume. RESUME Resumes paused playback. RESUME Resumes paused recording.

It may take some searching to find precisely the topic and/or command that you are looking for.

1.4 Matrices

MATLAB also works with matrices:

>> A = [1, 2, 3; 4, 5, 6; 7, 8, 0]

A =

1 2 3 4 5 6 7 8 0

>> b = [0; 1; 2]

b =

0 1 2

There are many builtin functions for solving matrix problems. For example, to solve the linear system Ax = b, type A\b:

>> x = A\b

x =

-0.

Note that the solution is printed out to only four decimal places. It is actually stored to about sixteen decimal places. (See Chapter ??.) To see more decimal places, you can type:

>> format long >> x

x =

-0.

Other options include format short e and format long e to display numbers using scientific notation.

1.7 Plotting

Tables and figures are usually more helpful than long strings of numerical results. Suppose you are interested in viewing a plot of cos(50x) for 0 ≤ x ≤ 1. You can create two vectors, one consisting of x-values and the other consisting of corresponding y = cos(50x) values, and use the MATLAB plot command. To plot the values of cos(50x) at x = 0, 0. 1 , 0. 2 ,... , 1, type

>> x = 0:0.1:1; % Form the (row) vector of x values. >> y = cos(50x); % Evaluate cos(50x) at each of the x values. >> plot(x,y) % Plot the result.

Note that the statement x = 0:0.1:1 behaves just like the for loop:

>> for i=1:11, x(i) = 0.1*(i-1); end;

Note also that, unless otherwise specified, each of these statements produces a row vector. In order to produce a column vector, one could replace x(i) in the above for loop by x(i,1), or one could replace the statement in the original code by x = [0:0.1:1]’;. Clearly, this small number of evaluation points will not produce very high resolution, as is seen in the plot produced by MATLAB depicted below.

−1 0 0.2 0.4 0.6 0.8 1

−0.

−0.

−0.

−0.

0

1

The plot command will graph the points (x(1), y(1)), (x(2), y(2)),.. ., which also implies that x and y must be vectors of the same length. We did not use enough points to achieve a high resolution. Therefore, we will change x to include more points and include a title and labels for the axes in the plot with the commands below:

>> x = 0:0.01:1; % Create a vector of 101 x values. >> plot(x,cos(50x)) % Plot x vs cos(50x), without (explicitly) storing cos(50*x). >> title(’Plot of x versus cos(50x)’) >> ylabel(’cos(50x)’) >> xlabel(’x’)

The plot resulting from these commands is:

−1 0 0.2 0.4 0.6 0.8 1

−0.

−0.

−0.

−0.

0

1 Plot of x versus cos(50x)

cos(50x)

x It is also possible to plot more than one function on the same graph. To plot the two functions f (x) = cos(x) and g(x) = x on the same graph, type:

>> plot(x,cos(50*x),x,x)

The result is shown below.

−1 0 0.2 0.4 0.6 0.8 1

−0.

−0.

−0.

−0.

0

1 cos(50x) x

Notice the small boxed legend on the plot. This was added to the plot with the following command:

legend(’cos(50x)’,’x’)

Another way to plot two functions on the same graph is to first plot one, then type hold on, and then plot the other. If you do not type hold on, then the second plot will replace the first, but this command tells MATLAB to keep plots on the screen after they are created. To go back to the default of removing old plots before new ones are added, type hold off. Again, type help plot for more information on plotting or type doc plot which posts the Helpdesk documentation on the plot command. Other useful commands are axis and plot3. For a bit of fun, type the following commands:

>> x = 0:0.001:10; >> comet(x,cos(3*x))

>> x = 0:.5:2; >> display(x) x = 0 0.5000 1.0000 1.5000 2.

In many cases, the extra carriage return imposed by the display command clutters printed results. Therefore, another helpful command is disp, which is similar to the display command.

>> disp(x) 0 0.5000 1.0000 1.5000 2.

You may still wish to have the variable name printed. Concatenating an array of text for output accomplishes this purpose.

>> disp([’x = ’,num2str(x)]) x = 0 0.5 1 1.5 2

For more information, type help num2str. Tables can be created such as the following:

>> disp(’ Score 1 Score 2 Score 3’), disp(rand(5,3)) Score 1 Score 2 Score 3 0.4514 0.3840 0. 0.0439 0.6831 0. 0.0272 0.0928 0. 0.3127 0.0353 0. 0.0129 0.6124 0.

You may find the fprintf command easier to use for tables of results. For instance, consider the simple loop:

>> fprintf(’ x sqrt(x)\n=====================\n’) for i=1:5, fprintf(’%f %f\n’,i,sqrt(i)), end x sqrt(x) ===================== 1.000000 1. 2.000000 1. 3.000000 1. 4.000000 2. 5.000000 2.

The fprintf command takes format specifiers and variables to be printed in those formats. The %f format indicates that a number will be printed in fixed point format in that location of the line, and the \n forces a carriage return after the two quantities i and sqrt(i) are printed. You can specify the total field width and the number of places to be printed after the decimal point by replacing %f by, say, %8.4f to indicate that the entire number is to be printed in 8 spaces, with 4 places printed after the decimal point. You can send your output to a file instead of the screen by typing:

fid = fopen(’sqrt.txt’,’w’); fprintf(fid,’ x sqrt(x)\n=================\n’); for i=1:5, fprintf(fid,’%4.0f %8.4f\n’,i,sqrt(i)); end

which prints the following table in a file called sqrt.txt:

x sqrt(x)

1 1. 2 1. 3 1. 4 2. 5 2.

Again, for more information, refer to MATLAB documentation.

1.10 More loops and conditionals

We have already seen how for loops can be used in MATLAB to execute a set of commands a given number of times. Suppose, instead, that one wishes to execute the commands until some condition is satisfied. For example, one might approximate a root of a given function f(x) by first plotting the function on a coarse scale where one can see the approximate root, then plotting appropriate sections on finer and finer scales until one can identify the root to the precision needed. This can be accomplished with the following MATLAB code:

xmin = input(’ Enter initial xmin: ’); xmax = input(’ Enter initial xmax: ’); tol = input(’ Enter tolerance: ’) while xmax-xmin > tol, x = [xmin:(xmax-xmin)/100:xmax]; y = f(x); plot(x,y) xmin = input(’ Enter new value for xmin: ’); xmax = input(’ Enter new value for xmax: ’); end;

The user looks at each plot to determine a value xmin that is just left of the root and a value xmax that is just right of the root. The next plot then contains only this section, so that closer values xmin and xmax can be determined. In the next chapter we discuss more efficient ways of finding a root of f(x). Another important statement is the conditional if statement. In the above code segment, one might wish to let the user know if the code happens to find a point at which the absolute value of f is less than some other tolerance, say, delta. This could be accomplished by inserting the following lines after the statement y = f(x);:

1.13 More advanced commands

It is perhaps apparent from the reference at the beginning of this chapter to the work on the Mars Exploration Rover, that MATLAB has a large number of commands. As we close this chapter, let us demonstrate some of the graphical capabilities through an example. The commands

[X,Y] = meshgrid(-3:.125:3); Z = peaks(X,Y); meshc(X,Y,Z); axis([-3 3 -3 3 -10 5])

produce the plot:

−3^ −

− 0 1

2 3

−

−

−

0

1

2

−10 3

−

0

5

In order to understand this plot, search MATLAB documentation for the commands meshgrid, peaks, meschc, and axis. While this chapter will get you started using MATLAB, effective use of the MATLAB documentation will be the key to proceeding to more complicated programs.

matlab’s origins

Cleve Moler – is chairman and chief scientist at The MathWorks. In the mid to late 1970s, he was one of the authors of LINPACK and EIS- PACK, Fortran libraries for numerical computing. To give easy access to these libraries to his students at the University of New Mexico, Dr. Moler invented MATLAB. In 1984, he co-founded The MathWorks with Jack Little to commercialize the MATLAB program. Cleve Moler received his bachelor’s degree from Caltech in 1961, and a Ph.D. from Stanford University. Moler was a professor of math and computer science for almost 20 years at the University of Michigan, Stanford University and the University of New Mexico. Before joining The MathWorks full time in 1989, he also worked for Intel Hypercube and Ardent. Dr. Moler was elected to the National Academy of Engineering in 1997. He has received honorary degrees from Link¨oping University, Sweden, the University of Waterloo and the Technical University of Denmark.

Exercises

  1. Run the examples in this chapter using MATLAB to be sure that you see the same results.
  2. With the following matrices and vectors:

A =

, B =

, v =

, w =

compute the following both by hand and in MATLAB.

(a) vT^ w (b) vwT (c) Av (d) AT^ v (e) AB

(f) BA (g) A^2 (= AA) (h) The vector y for which By = w. (i) The vector x for which Ax = v.

  1. Use MATLAB to produce a single plot displaying the graphs of the functions sin(kx) across [0, 2 π], for k = 1,... , 5.
  2. Use MATLAB to print a table of values x, sin(x), and cos(x), for x = 0, π 6 , 26 π ,... , 2 π. Label the columns of your table.