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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

School of Mathematical Sciences<br />

Monash University<br />

a = 2; b = 1; c = 5;<br />

if ( abs(a) > 1e-10 )<br />

if ( b*b - 4*a*c ) >= 0 )<br />

r_1 = ( -b + (b*b - 4*a*c)^(1/2) )/(2*a) ;<br />

r_2 = ( -b - (b*b - 4*a*c)^(1/2) )/(2*a) ;<br />

else<br />

r_1 = 0;<br />

r_2 = 0;<br />

end<br />

else<br />

r_1 = -c/b;<br />

r_2 = r_1;<br />

end;<br />

The message here is never test two real numbers for equality. Thus if the mathematics<br />

tells you something special happens when p = q (for example) then in your<br />

Matlab code you should never use an if statement like<br />

if (p == q)<br />

· · ·<br />

end<br />

but rather<br />

if abs(p - q) < very_small<br />

· · ·<br />

end<br />

There still remains the niggling problem of how <strong>to</strong> handle the case where both a and b<br />

are zero. Here I invoke the classic excuse of a lecturer – this case is left as an exercise<br />

for the student.<br />

2.3 A finite series<br />

How would you get Matlab <strong>to</strong> compute the following sum<br />

S = 1 + 1 2 + 1 3 + 1 4 + · · · + 1<br />

100<br />

This seems simple enough, just add up 100 numbers. Too easy really (agreed?). If you<br />

were <strong>to</strong> compute this by hand (always a good place <strong>to</strong> start when writing computer code)<br />

you most probably would start with the first term, add on the second term, then the<br />

16-Feb-2014 18

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

Saved successfully!

Ooh no, something went wrong!