Page 85 - Numerical Analysis Using MATLAB and Excel
P. 85

Chapter 2  Root Approximations




                      function y= exercise2(x);
                      y = sqrt(2.*x+1)−sqrt(x+4);
                      After saving this file as exercise2.m, we execute the following program:


                      x1=2.1; x2=4.3; tol=0.00001;      %  If we specify x1=a=2 and x2=b=4, the program
                      % will not display any values because xm=(x1+x2)/2 = 3 = answer
                      disp('    xm            fm'); disp('-------------------------')
                      while (abs(x1-x2)>2*tol);
                         f1=exercise2(x1); f2=exercise2(x2); xm=(x1+x2)/2;
                         fm=exercise2(xm);
                         fprintf('%9.6f %13.6f \n', xm,fm);
                         if (f1*fm<0);
                         x2=xm;
                         else
                           x1=xm;
                         end
                      end
                   When this program is executed, MATLAB displays the following:


                         xm            fm
                      -------------------------
                      3.200000      0.037013
                      2.650000     -0.068779
                      2.925000     -0.014289
                      3.062500      0.011733
                      2.993750     -0.001182
                      3.028125      0.005299
                      3.010938      0.002065
                      3.002344      0.000443
                      2.998047     -0.000369
                      3.000195      0.000037
                      2.999121     -0.000166
                      2.999658     -0.000065
                      2.999927     -0.000014
                      3.000061      0.000012
                      2.999994     -0.000001
                      3.000027      0.000005
                      3.000011      0.000002










               2−32                             Numerical Analysis Using MATLAB® and Excel®, Third Edition
                                                                             Copyright © Orchard Publications
   80   81   82   83   84   85   86   87   88   89   90