関数 f(x) について f(c)=0 となる c がひとつだけ存在するとき、


適当な項



ただし、三角関数のように接線が x 軸と平衡になってしまうようなケースなど、条件によってはうまくいかないケースもあるので、注意が必要です。
接線は




区間 [a,b] で f(a) と f(b) が同符号である場合、永久ループとなってしまうことに気をつけてください。
// ver.041108
#ifndef __NEWTON_H
#define __NEWTON_H
#include <cmath>
// Function: y=0 を求めたい関数
// FunctionD: Function の微分関数
// x: 初項
// e: 終了条件 第n項と第n+1項の差
double Newton(double (*Function)(double), double (*FunctionD)(double), double x, double e)
{
double x2 = x;
do{
x = x2;
x2 = x - Function(x) / FunctionD(x);
}while(fabs(x2 - x) >= e);
return x2;
}
#endif
#include <iostream>
#include <cmath>
using namespace std;
#include "../Newton.h"
double F(double x);
double FD(double x);
main()
{
cout << Newton(F, FD, 0.5, pow(10.0, -10.0)) << endl;
return 0;
}
double F(double x)
{
return cos(x);
}
double FD(double x)
{
return -sin(x);
}