03.03.2014 Views

Numerical Methods Course Notes Version 0.1 (UCSD Math 174, Fall ...

Numerical Methods Course Notes Version 0.1 (UCSD Math 174, Fall ...

Numerical Methods Course Notes Version 0.1 (UCSD Math 174, Fall ...

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.

2.4. PLOTTING 21<br />

Exercises<br />

(2.1) What do the following pieces of octave/Matlab code accomplish?<br />

(a) x = (0:40) ./ 40;<br />

(b) a = 2;<br />

b = 5;<br />

x = a + (b-a) .* (0:40) ./ 40;<br />

(c) x = a + (b-a) .* (0:40) ./ 40;<br />

y = sin(x);<br />

plot(x,y);<br />

(2.2) Implement the naïve quadratic formula to find the roots of x 2 + bx + c = 0, for real b, c. Your<br />

code should return<br />

−b ± √ b 2 − 4c<br />

.<br />

2<br />

Your m-file should have header line like:<br />

function [x1,x2] = naivequad(b,c)<br />

Test your code for (b, c) = ( 1 × 10 15 , 1 ) . Do you get a spurious root?<br />

(2.3) Implement a robust quadratic formula (cf. Example Problem 1.9) to find the roots of x 2 +<br />

bx + c = 0. Your m-file should have header line like:<br />

function [x1,x2] = robustquad(b,c)<br />

Test your code for (b, c) = ( 1 × 10 15 , 1 ) . Do you get a spurious root?<br />

(2.4) Write octave/Matlab code to find a fixed point for the cosine, i.e., some x such that x =<br />

cos(x). Do this as follows: pick some initial value x 0 , then let x i+1 = cos(x i ) for i =<br />

0, 1, . . . , n. Pick n to be reasonably large, or choose some convergence criterion (i.e., terminate<br />

if |x i+1 − x i | < 1 × 10 −10 ). Does your code always converge?<br />

(2.5) Write code to implement the factorial function for integers:<br />

function [nfact] = factorial(n)<br />

where n factorial is equal to 1 · 2 · 3 · · · (n − 1) · n. Either use a ‘for’ loop, or write the function<br />

to recursively call itself.

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

Saved successfully!

Ooh no, something went wrong!