15.11.2014 Views

Chapter 4: Programming in Matlab - College of the Redwoods

Chapter 4: Programming in Matlab - College of the Redwoods

Chapter 4: Programming in Matlab - College of the Redwoods

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.

310 <strong>Chapter</strong> 4 <strong>Programm<strong>in</strong>g</strong> <strong>in</strong> <strong>Matlab</strong><br />

We start by sett<strong>in</strong>g tol=5e-4. The <strong>in</strong>tent is to loop until <strong>the</strong> relative error<br />

is less than this tolerance, which signifies that we have 4 signicant digits <strong>in</strong> our<br />

approximation <strong>of</strong> π 2 /6 us<strong>in</strong>g <strong>the</strong> <strong>in</strong>f<strong>in</strong>ite series. The variable s will aga<strong>in</strong> conta<strong>in</strong><br />

<strong>the</strong> runn<strong>in</strong>g sum and we aga<strong>in</strong> <strong>in</strong>itialize <strong>the</strong> runn<strong>in</strong>g sum to zero. The variable k<br />

conta<strong>in</strong>s <strong>the</strong> term number, so we <strong>in</strong>itialize k to 1. We next <strong>in</strong>itialize rel_error<br />

to 1 so that we enter <strong>the</strong> while loop at least once.<br />

tol=5e-4;<br />

s=0;<br />

k=1;<br />

rel_error=1;<br />

Each pass through <strong>the</strong> loop, we do three th<strong>in</strong>gs:<br />

1. We update <strong>the</strong> runn<strong>in</strong>g sum by add<strong>in</strong>g <strong>the</strong> next term <strong>in</strong> <strong>the</strong> series to <strong>the</strong><br />

previous runn<strong>in</strong>g sum. This is accomplished with <strong>the</strong> statement s=s+1/k^2.<br />

2. We <strong>in</strong>crement <strong>the</strong> term number by 1, us<strong>in</strong>g <strong>the</strong> statement k=k+1 for this<br />

purpose.<br />

3. We calculate <strong>the</strong> current relative error.<br />

We cont<strong>in</strong>ue to loop while <strong>the</strong> relative error is greater than or equal to <strong>the</strong><br />

tolerance.<br />

while rel_error>=tol<br />

s=s+1/k^2;<br />

k=k+1;<br />

rel_error=abs(s-pi^2/6)/abs(pi^2/6);<br />

end<br />

When <strong>the</strong> loop is completed, we use fpr<strong>in</strong>tf to output results.<br />

fpr<strong>in</strong>tf(’The actual value <strong>of</strong> pi^2/6 is %f.\n’, pi^2/6)<br />

fpr<strong>in</strong>tf(’The sum <strong>of</strong> <strong>the</strong> first %d terms is %f.\n’, k-1, s)<br />

fpr<strong>in</strong>tf(’The relative error is %f.\n’, rel_error)<br />

The results follow.

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

Saved successfully!

Ooh no, something went wrong!