使用牛顿迭代法求根 一元三次方程的根

来源:互联网 发布:mac内胆包 编辑:程序博客网 时间:2024/04/30 02:20

牛顿迭代法(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函数
usingnamespace std;
 
doublef(int,int,int,int,double);//函数声明
doublef1(int,int,int,int,double);
doubleget_solution(int,int,int,int,double);
 
intmain()
{
inta,b,c,d;
doublesolution,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)//当求得的根很小时,直接让它为0
solution_value=0;
cout<<"the solution near "<<solution<<" is "<<solution_value<<endl;
 
getchar();
return0;
 
}
 
doublef(intw_f,intx_f,inty_f,intz_f,doublesol_f)//当根为x时,用来求f(x)的值
{
doublef_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; //调试时用
returnf_result;
}
 
doublef1(intw_f1,intx_f1,inty_f1,intz_f1,doublesol_f1) //当根为x时,用来求f'(x)的值
{
doublef1_result=3*w_f1*pow(sol_f1,2)+2*x_f1*sol_f1+y_f1;
//cout<<"f1_result is "<<f1_result<<endl;//调试时用
returnf1_result;
}
 
doubleget_solution(intw,intx,inty,intz,doublesol) //求根函数,调用了上面两个函数
{
doublevalue,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时就认为取到了值
 
returnvalue;
}

测试例子: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 x
2 1 1 -22
2.1
the solution near 2.1 is 2

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


本文转载自http://www.node-net.org/read.php?53

原创粉丝点击