二分法
この計算・判定を繰り返して(x1-x2)の絶対値がある値以下(例えば、1.0E-6等)になれば、(x1+x2)/2が確からしい解と推定される。
この考え方を用いて、下記の関数の解を数値的に求めてみよ。
以下にヒントを示す。
#include<stdio.h>
#include<math.h>
#define MAXNUM 1000 ← 繰り返しの最大数
#define EPS 1.e-6 ← 収束判定の基準(x1-x2の絶対値がこれより小さくなったら計算終了)
double f(double x) ← 今問題としている関数
{
return(x - exp(-x) + sin(x));
}
main()
{
double x1, x2, mid_x; ← 挟み込む変数x1, x2と中間点mid_x
int i;
x1 = -100.0; ← x1の初期値
x2 = 100.0; ← x2の初期値
for(i = 0; i < MAXNUM; ++i){
ここを考えてみよう!
if(fabs(x1 - x2) < EPS){ ← ここで用いている組み込み数学関数fabs()は実数の絶対値を与える
printf("Ans. = %lf (Iteration No. = %d)\n", (x1+x2)/2, i);
break;
}
}
}
以下に実行結果例を示す。
There should be an answer! (x1 = -100.000000 x2 = 100.000000)
There should be an answer! (x1 = 0.000000 x2 = 100.000000)
There should be an answer! (x1 = 0.000000 x2 = 50.000000)
There should be an answer! (x1 = 0.000000 x2 = 25.000000)
There should be an answer! (x1 = 0.000000 x2 = 12.500000)
There should be an answer! (x1 = 0.000000 x2 = 6.250000)
There should be an answer! (x1 = 0.000000 x2 = 3.125000)
There should be an answer! (x1 = 0.000000 x2 = 1.562500)
There should be an answer! (x1 = 0.000000 x2 = 0.781250)
There should be an answer! (x1 = 0.000000 x2 = 0.390625)
There should be an answer! (x1 = 0.195312 x2 = 0.390625)
There should be an answer! (x1 = 0.292969 x2 = 0.390625)
There should be an answer! (x1 = 0.341797 x2 = 0.390625)
There should be an answer! (x1 = 0.341797 x2 = 0.366211)
There should be an answer! (x1 = 0.354004 x2 = 0.366211)
There should be an answer! (x1 = 0.354004 x2 = 0.360107)
There should be an answer! (x1 = 0.354004 x2 = 0.357056)
There should be an answer! (x1 = 0.354004 x2 = 0.355530)
There should be an answer! (x1 = 0.354004 x2 = 0.354767)
There should be an answer! (x1 = 0.354385 x2 = 0.354767)
There should be an answer! (x1 = 0.354385 x2 = 0.354576)
There should be an answer! (x1 = 0.354385 x2 = 0.354481)
There should be an answer! (x1 = 0.354433 x2 = 0.354481)
There should be an answer! (x1 = 0.354457 x2 = 0.354481)
There should be an answer! (x1 = 0.354457 x2 = 0.354469)
There should be an answer! (x1 = 0.354463 x2 = 0.354469)
There should be an answer! (x1 = 0.354463 x2 = 0.354466)
There should be an answer! (x1 = 0.354463 x2 = 0.354464)
Ans. = 0.354463 (Iteration No. = 27)
電卓等を用いて、実際に求められた値を用いてf(x)がゼロに限りなく近いことを確認せよ。ここで注目すべきことは、全繰り返し数(27回)の内、13回程度は0.35まで求められた後に精度を上げるために費やされている点。解答例はこちら。