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 />

What more do we need <strong>to</strong> make this code work?<br />

We need values for a,b and c. This is easy – we simply include lines like a = 2; b =<br />

1; c = 5; before the above pair of lines.<br />

What can go wrong with this code?<br />

We might encounter complex roots. Though Matlab can handle complex numbers (without<br />

any fuss) we’ll declare (for this example) that complex roots are forbidden. So we<br />

need <strong>to</strong> avoid computing the square root when b 2 − 4ac < 0. This we do by using an if<br />

statement.<br />

Here is our updated code.<br />

a = 2; b = 1; c = 5;<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 />

end<br />

Notes<br />

◮ The ; also allows us <strong>to</strong> put more than one expression on each line.<br />

◮ The if (...) and end lines define the block of lines <strong>to</strong> be executed only when<br />

b 2 − 4ac is greater or equal <strong>to</strong> zero.<br />

If we left the code as it is we could run in<strong>to</strong> another problem further down the track.<br />

How so?. Well, we have deliberately chosen (or forgotten?) <strong>to</strong> not set the values for r 1<br />

and r 2 in the case of complex roots. But what would happen if we tried <strong>to</strong> use r 1 and<br />

r 2 later, in some other part of the code? Heaven only knows what values would be used<br />

(never assume that a variable starts with an initial value of zero). Clearly we need <strong>to</strong><br />

provide values for r 1 and r 2 for all possible cases. Thus we modify the if statement<br />

as follows<br />

a = 2; b = 1; c = 5;<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 />

Note that setting r 1 = 0 and r 2 = 0 is mathematically wrong but at least we can<br />

now proceed with known values for r 1 and r 2. We could also use these zero values as<br />

16-Feb-2014 16

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

Saved successfully!

Ooh no, something went wrong!