牛顿迭代法(Newton’s method)又称为牛顿-拉夫逊方法(Newton-Raphson method),它是牛顿在17 世纪提出的一种在实数域和复数域上近似求解方程的方法。多数方程不存在求根公式,因此求精确根非常困难,甚至不可能,从而寻找方程的近似根就显得特别重要。方法使用函数f(x)的泰勒级数的前面几项来寻找方程f(x) = 0的根。牛顿迭代法是求方程根的重要方法之一,其最大优点是在方程f(x) = 0的单根附近具有平方收敛,而且该法还可以用来求方程的重根、复根。另外该方法广泛用于计算机编程中。
设r是f(x) = 0的根,选取x0作为r初始近似值,过点(x0,f(x0))做曲线y = f(x)的切线L,L的方程为y = f(x0)+f’(x0)(x-x0),求出L与x轴交点的横坐标 x1 = x0-f(x0)/f’(x0),称x1为r的一次近似值。过点(x1,f(x1))做曲线y = f(x)的切线,并求该切线与x轴交点的横坐标 x2 = x1-f(x1)/f’(x1),称x2为r的二次近似值。重复以上过程,得r的近似值序列,其中x(n+1)=x(n)-f(x(n))/f’(x (n)),称为r的n+1次近似值,上式称为牛顿迭代公式。
解非线性方程f(x)=0的牛顿法是把非线性方程线性化的一种近似方法。把f(x)在x0点附近展开成泰勒级数 f(x) = f(x0)+(x-x0)f’(x0)+(x-x0)^2*f”(x0)/2! +… 取其线性部分,作为非线性方程f(x) = 0的近似方程,即泰勒展开的前两项,则有f(x0)+f’(x0)(x-x0)=f(x)=0 设f’(x0)≠0则其解为x1=x0-f(x0)/f’(x0) 这样,得到牛顿法的一个迭代序列:x(n+1)=x(n)-f(x(n))/f’(x(n))。
//由于算法的限制,这个程序求得的根并不能保证一定是距输入估计值最近的根,但一定是方程的根
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #include<iostream>#include<stdio.h>#include<cmath>//调用了fabs、pow函数using namespace std;double f( int , int , int , int , double ); //函数声明double f1( int , int , int , int , double );double get_solution( int , int , int , int , double );int main(){int a,b,c,d;double solution,solution_value;cout<< "pls input the parameters of the equation a,b,c,d;and the estimate x" <<endl;cin>>a>>b>>c>>d>>solution;solution_value=get_solution(a,b,c,d,solution);if (solution_value<=1e-5) //当求得的根很小时,直接让它为0solution_value=0;cout<< "the solution near " <<solution<< " is " <<solution_value<<endl;getchar ();return 0;}double f( int w_f, int x_f, int y_f, int z_f, double sol_f) //当根为x时,用来求f(x)的值{double f_result=w_f* pow (sol_f,3)+x_f* pow (sol_f,2)+y_f*sol_f+z_f;//cout<<"f_result is "<<f_result<<endl; //调试时用return f_result;}double f1( int w_f1, int x_f1, int y_f1, int z_f1, double sol_f1) //当根为x时,用来求f'(x)的值{double f1_result=3*w_f1* pow (sol_f1,2)+2*x_f1*sol_f1+y_f1;//cout<<"f1_result is "<<f1_result<<endl;//调试时用return f1_result;}double get_solution( int w, int x, int y, int z, double sol) //求根函数,调用了上面两个函数{double value,tmp;value=sol;do //使用了x1=x0-f(x0)/f'(x0),不断循环逼近{tmp=f(w,x,y,z,value);value=value-tmp/f1(w,x,y,z,value);//cout<<"funciont_value is "<<tmp<<";value is "<<value<<endl;//调试时用} while ( fabs (tmp)>=1e-5); //当式子的值与0的绝对值小于1e-5时就认为取到了值return value;} |
测试例子:ax^3 +b x^2+cx+d=0,所以运行时候分别输入a=2,b=1,c=1,d=-14,以及求X在某个值附近的根,比如2.1
pls input the parameters of the equation a,b,c,d;and the estimate x2 1 1 -222.1the solution near 2.1 is 2