課題:二分法による根の計算

課題二分法によって,$[0.1,1]$の中で$1/x^2-2=0$の根を計算しなさい。 ($N=20, TOL=10^{-5}$)

計算の結果を以下の表に入れてください。

Step a b p b-a
1 0.1 1 0.55 0.45
... ... ... ... ...
In [3]:
%初期化
a=0.1;
b=1;
N=20;
TOL=1e-5;
format long;    % 多くの有効数字を表示するように
i=1;
FA=1/(a*a)-2.0;
A=[];
while(i<=N && (b-a)/2.0 > TOL)
  p=(a+b)/2.0;
  FP=1/(p*p)-2.0;
  A(i,1:4)=[a,b,p,b-a];     % a,b,pを行列に保存する
    if(abs(FP) < 1E-10)     % While ループを終了する
       break;
    end
  i=i+1;
  if(FA*FP>0)
      a=p;
      FA=FP;
  else
      b=p;
  end
end
if( i <= N )
  disp('Solution is found:');
  disp(p);
else
  disp('Solution is not found after N interations.')
end
Out[3]:
Solution is found:
 0.707118225097656
In [4]:
%The list of a, b and p in the iteration:
disp(A)
Out[4]:
 Columns 1 through 3:

   1.00000000000000e-01   1.00000000000000e+00   5.50000000000000e-01
   5.50000000000000e-01   1.00000000000000e+00   7.75000000000000e-01
   5.50000000000000e-01   7.75000000000000e-01   6.62500000000000e-01
   6.62500000000000e-01   7.75000000000000e-01   7.18750000000000e-01
   6.62500000000000e-01   7.18750000000000e-01   6.90625000000000e-01
   6.90625000000000e-01   7.18750000000000e-01   7.04687500000000e-01
   7.04687500000000e-01   7.18750000000000e-01   7.11718750000000e-01
   7.04687500000000e-01   7.11718750000000e-01   7.08203125000000e-01
   7.04687500000000e-01   7.08203125000000e-01   7.06445312500000e-01
   7.06445312500000e-01   7.08203125000000e-01   7.07324218750000e-01
   7.06445312500000e-01   7.07324218750000e-01   7.06884765625000e-01
   7.06884765625000e-01   7.07324218750000e-01   7.07104492187500e-01
   7.07104492187500e-01   7.07324218750000e-01   7.07214355468750e-01
   7.07104492187500e-01   7.07214355468750e-01   7.07159423828125e-01
   7.07104492187500e-01   7.07159423828125e-01   7.07131958007813e-01
   7.07104492187500e-01   7.07131958007813e-01   7.07118225097656e-01

 Column 4:

   9.00000000000000e-01
   4.50000000000000e-01
   2.25000000000000e-01
   1.12500000000000e-01
   5.62499999999999e-02
   2.81250000000000e-02
   1.40625000000000e-02
   7.03124999999993e-03
   3.51562500000002e-03
   1.75781249999996e-03
   8.78906249999978e-04
   4.39453124999933e-04
   2.19726562500022e-04
   1.09863281249956e-04
   5.49316406249778e-05
   2.74658203125444e-05
In [ ]: