28.11.2014 Views

MTH3051 Introduction to Computational Mathematics - User Web ...

MTH3051 Introduction to Computational Mathematics - User Web ...

MTH3051 Introduction to Computational Mathematics - User Web ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

School of Mathematical Sciences<br />

Monash University<br />

looping as each term is calculated. Here is the final code<br />

% --- set initial values ----------------------------------------<br />

k = 0;<br />

x = 1.23;<br />

sum = 1;<br />

term = 1;<br />

k_max = 100;<br />

looping = true;<br />

x_square = x*x;<br />

% --- compute successive terms in the series --------------------<br />

while looping<br />

end<br />

k = k + 1;<br />

term = - term*x_square/( (2*k)*(2*k-1) );<br />

sum = sum + term;<br />

if ( abs(term) < 0.00001 )<br />

looping = false;<br />

end<br />

if ( k > k_max )<br />

looping = false;<br />

end<br />

answer = sum;<br />

There are quite a few changes introduced in the above code. We have replaced the for<br />

loop with a while loop. Thus we have also been forced <strong>to</strong> explicitly increment k (i.e.<br />

the line k = k + 1) and <strong>to</strong> limit the number of terms (hence the new variable k max).<br />

Though the above code is longer than the previous version it is (in my opinion) easier <strong>to</strong><br />

read and better conveys what we are actually doing (i.e. looping until we reach a given<br />

accuracy).<br />

Compare this code with that given for sin(x) at the start of these notes. You will see<br />

that they are similar but they do have important differences (as they should, after all<br />

sin(x) and cos(x) are different functions). Note in particular the way term is calculated,<br />

and the initial values for k and sum. If you have any doubts that they are correct one<br />

way <strong>to</strong> check is <strong>to</strong> follow the Matlab code (pretend you are the computer) and following<br />

(writing out) the loops for the first few terms. You will very quickly see that both<br />

programs as written are correct.<br />

16-Feb-2014 24

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!