| newton.c |
/*
* newton.c -- Newton 法で方程式 f(x)=0 を解く
* コンパイル gcc -o newton newton.c -lm
* いずれも実行可能ファイルの名前は newton で、実行は ./newton
*/
#include <stdio.h>
#include <math.h>
int main ()
{
int i, maxitr = 100;
double f(double), dfdx(double), x, dx, eps;
printf(" 初期値 x0, 許容精度ε=");
scanf("%lf%lf", &x, &eps);
for (i = 0; i < maxitr; i++) {
dx = - f(x) / dfdx(x);
x += dx;
printf("f(%20.15f)=%9.2e\n", x, f(x));
if (fabs(dx) <= eps)
break;
}
return 0;
}
double f(double x)
{
return cos(x) - x;
}
/* 関数 f の導関数 (df/dx のつもりで名前をつけた) */
double dfdx(double x)
{
return - sin(x) - 1.0;
}
|
を初期値として、許容精度
を指示して Newton 法で解かせ
たのが以下の結果 (入力は 1 1e-15)。
isc-xas06% gcc -o newton newton.c -lm isc-xas06% ./newton 初期値 x0, 許容精度ε=1 1e-15 f( 7.503638678402439e-01)=-1.89e-02 f( 7.391128909113617e-01)=-4.65e-05 f( 7.390851333852840e-01)=-2.85e-10 f( 7.390851332151607e-01)= 0.00e+00 f( 7.390851332151607e-01)= 0.00e+00 isc-xas06% |