Sei sulla pagina 1di 8

CHEN 14010

Matlab Semester 2

AJM & PC

MATLAB Semester 2, 2010


Over the next four weeks we will practice more programming in MATLAB in readiness for the online assessment on Tuesday 2nd March, 2010 (Week 5). To help you do this test, you are advised to work through all the exercises and save your programs onto My Documents and/or a pen drive. In Week 6, you will receive another handout in readiness for the second and final online assessment on Tuesday April 27th (Week 10). You will find the Semester 1 handouts useful for this. No new programming techniques will be introduced the aim to increase your ability to use the methods you have already met. In particular we will focus on loops and if statements. 1. Quadrature exercises

(a) Trapezium rule The trapezium rule gives an approximation to a definite integral, viz.

f ( x) dx h
a

fo + fn + f 1 + f 2 + + f n 2 + f n 1 2

(1) We have divided the interval [a, b] into n equal strips of width h. Thus h =
b a n
f i = f ( a + ih )

We have used the notation

so f o = f (a ) and f n = f (a + nh ) = f (b) . The task is to write a MatLab program that can integrate a user-defined function over a given range using a given number of strips. (i) Structure of program The overall package will consist of a main program (e.g. quadtrap.m) and two function m-files (e.g. trap.m and f.m), where trap.m performs the trapezium rule and f.m provides the function to be integrated. The f.m file is very much like the one you used last semester doing the NewtonRaphson method, e.g. function y = f(x) y = whatever you want it to be;

CHEN 14010

Matlab Semester 2

AJM & PC

The trap.m routine needs to be told the end points of the integral (i.e. a and b), the number of strips (i.e. n). It then asks the routine above for the values of the function at all points required. You thus need a structure like; function y = trap(a, b, n) sum = 0.5*( f(a) + f(b) ); % First term on RHS of eq. 1 Calculate h; for i = 1: n-1 % Loop over all the middle values sum = sum + function value required in eq. 1; end y = h*sum; % Remember the h multiplication in eq. (1) Do make sure you understand how the loop works and why this routine evaluates the RHS of eq. (1). Please note that here and elsewhere, the program structure is indicated, not the precise content. For example, you need to provide the expression for h you dont type in calculate h ! Also please note that this routine might not work for n = 1 (why?). Finally, at least for the first exercise, the main program will have a structure like: a = input( Value of a: ); b = input( Value of b: ); n = input( Value of n: ); truth = true value of integral; print out truth and trap(a, b, n) (ii) Trying it out
1 )= , and let a = 1 and b = 2. Calculate the value of this integral Ex. 1: Set f(x x analytically i.e. truth in the program above.

% You need to work this out

Now use the trapezium rule to calculate this integral using n = 4, 8 and 16 strips and check you are steadily approaching the right answer. Ex. 2: Modify the program by introducing a for loop into the main program, so that the program prints out a table, showing how the trapezium result varies for n = 4, 6, 8, 10, up to n = 20. To print out the numbers a, b &c on one line, type disp([a, b, c]). Ex. 3: Further modify the program so that for each value of n, you get a print out of the error, i.e. the absolute value of the difference between the trapezium value and truth. The MatLab function abs(x) returns the absolute value of x.

CHEN 14010

Matlab Semester 2

AJM & PC

2 Ex. 4: Use MatLab to plot the error against 1n . Do you get a straight line for reasonably large values of n?

To do this, it is helpful to have two arrays, x and y. You will need to think of providing a counter, step for example, so that step is incremented by one each time 2 you go round the loop. Then x(step) will contain the value of 1n for that loop and y(step) will contain the corresponding error. At the end of the loop, you have: plot(x,y). Ex. 5: Now modify the program so that at each iteration, n is doubled. Thus you should get a print out for n = 4, 8, 16, 32 up to n = 1024. Ex. 6: Now use the while construction, so that the computer keeps on doubling n until the value of the error get less than a user defined tolerance, tol. What value of n is needed to get the error less that 1.0e-3, 1.0e-6 and 1.0e-8 ? You will thus need to alter the main program so it has a structure like User provides value of tol. error = 100*tol % make sure error>tol before you start! truth = ??? % provide the true answer n = 2; Provide values of a and b while error > tol n = 2*n; % double the value of n. The first value is 4. get trapezium value of integral calculate the error print out n and the error end; if error < tol, then print out n, error % naturally you cannot type this as is! Make sure you understand how the while loop works. The computer will carry on doubling n until the condition error > tol is false, whereupon it will leave the loop. The value of n finally printed out is the value you need. Ex. 7: A problem with while loops is that if something goes wrong, the condition might never be met and the loop will never stop. If you run a program and it never stops, type ctrl c to end it! It is good practice to prevent while loops lasting for ever. To do this you can have a counter in the loop and ensure that the counter never exceed a certain value. We did this in the Newton-Raphson program. Modify your quadrature program so the while loop cannot do more than nmax iterations. You will need some extra lines like: User provides nmax 3

CHEN 14010

Matlab Semester 2

AJM & PC

steps = 0; while error > tol & (steps < nmax) steps = steps + 1; Etc. end; if (steps >= nmax) Print message saying nmax steps exceeded. else Print out n and error end if Ex. 8: Usually you do not use numerical methods to work out an integral you already know! If you do not know the value of truth, then you usually estimate the accuracy of your estimate by comparing the difference between two successive iterations. Modify your program so that it keeps on doubling n until the difference between the estimates from two successive iterations (diff) is less than tol. To do this, you could save the trapezium estimate for each value of n used, but this is a bit wasteful in terms of storage and is not very elegant. Better is just to use two variables and continually update them. Try something along these lines: Provide normal input data including tol; diff = 100*tol; n=4; old = trap (a, b, n); % this contains the first estimate while diff > tol and (steps < nmax) n = 2*n; %double n new = value of trap with new value of n; diff = absolute difference between old and new; old = new; % we copy the last estimate, new, into old End; Make sure you understand how this old/new business works! Each time, when you go into an iteration, old contains the previous value of the estimate and new contains the new one. The while loop keeps on going until diff becomes less than tol (or you exceed the maximum number of iterations if something has gone wrong!). Test your program by working out how many iterations are needed to get diff < 1.0e-3, 1.0e-6 and 1.0e-8. You are now in a position to calculate the integral of whatever function you like to your specified accuracy!

CHEN 14010 (iii) Simpsons Rule

Matlab Semester 2

AJM & PC

Another way to do quadrature is to use Simpsons Rule.


b

f x
a

dx

h f f 3 o

2n 4

[ f 1 f 3. . . f 2n1] 2 [ f 2 f 4. . . f 2n 2 ]

(2) We have divided the interval [a, b] into 2n equal strips of width h. Thus h=
ba . 2 n

You will note that the odd numbered points have a different multiplying factor than the even numbered points. There are many ways of doing this within Matlab one way is to have two for loops, viz. for i = 1:2:2n-1 for the odd numbers and for i = 2:2: 2n-2 for the even numbers. The task now is to do quadrature with MatLab using Simpsons Rule. Keep the same structure as your trapezium program, but have a different function m file, simpson.m Ex. 9: Repeat ex. 8 but using Simpsons rule to do the quadrature rather than the trapezium rule. For the same number of strips, is Simpson more or less accurate than the trapezium rule? 2. Bisection method for finding roots

A robust way to solve f(x) = 0, is the bisection method. Let us suppose the solution is x0. It works by noting that the function change sign as one passes from x < x0 to x > x0 (except in very rare cases, where the function has a maximum or minimum at the root). Suppose we can bracket the root. That is we know two values of x, i.e. x1 and x2, for which the function has different signs. Then we know the root lies inbetween these two values. The bisection method works by calculating the mid-point, xm = i d

x +x2 1 . 2

xi . We then calculate f( m ) There are now two possibilities. d

xi (i) f( m )has the opposite sign to f ( x1 ) . In that case the root lies between d xmid and x1.

CHEN 14010

Matlab Semester 2

AJM & PC

xi x . (ii) f( m )has the opposite sign to f ( 2) In that case the root lies between. d xmid and x2.
In either case you have now halved the interval in which you know the root must like. The bisection method proceeds by reducing this interval each iteration until you know the answer to your required accuracy. (i) Structure of program The overall package will consist of a main program (e.g. bisection.m) and a function m-file (e.g. f.m), where f.m provides the function whose root you seek. Initially you will need to give the program values of x1 and x2. You need to check the function has opposite signs for these two values. Suppose you want the program to do n iterations.

CHEN 14010

Matlab Semester 2

AJM & PC

Then the structure of bisection.m will be something like this: User provides values for n, x1 and x2; Check f(x1)*f(x2) < 0 If not, write out a warning message. for i = 1:n Calculate xmid; if f(xmid)*f(x1) < 0 % root inbetween xmid and x1 x2 = xmid; % x2 takes on xmid value else % root must lie between xmid and x2 x1 = xmid end % interval halved. Root lies between x1 and x2 print out i, x1, x2 and f(x1), f(x2) end % end of for loop

() x= . Ex. 1 Solve f x=2 2 0


Take as initial guesses 0 and 2 and do 6 iteration (n=6). Compare with the exact root. Ex. 2: Normally you want to carry on iterating until you get the root to a given accuracy. Use a while construction to keep on iterating until you know the interval containing the root is less than a user-defined tolerance. The interval is abs(x1-x2). Thus you must modify the program so that you calculate the root in ex. 1 to within an interval of tol. Run the program for tol = 1.0e-2, 1.0e-4 and 1.0e-6. 3. Secant method for finding roots Another way to find a root is to use the secant method. Given two estimates of the root, x1 and x2, the secant method generates a new estimate, x3, according to

x3 =

x2 f ( x1 ) x1 f ( x2 ) f ( x1 ) f ( x2 )

For the next iteration, we use x2 and x3 to get the next estimate, and so on. This method does not require you to know the derivative of the function (unlike Newton-Raphson) and, if it converges, it is generally much quicker than the bisection method. Just like Newton-Raphson, however, convergence is far from guaranteed!

() x= so Ex. 1: Write a secant program to solve f x=2 2 0 that the estimated relative x x2 error (i.e. abs 1 x ) is less than tol. Also ensure that you never do more than 1 nmax iterations. (Some of this is very similar to Semester 1s Newton-Raphson program). Take as initial guesses for the root x1 = 0 and x2 = 2.

CHEN 14010

Matlab Semester 2

AJM & PC

You will need to keep track of your estimates of the root. When you have calculated x3 in the program and calculated the relative error (which you are testing in your while loop), you need to have something within the loop like x1 = x2; x2 = x3; Think carefully why the lines are in this order. Why would it be wrong to have the following? x2 = x3; x1 = x2;

Potrebbero piacerti anche