原题目:用埃特肯法求方程x^3-x^2-1=0在x0=1.5附近的根,ε=10^-4.
网上找了一个开三次根方法的,但是代码好像不太友好 http://blog.itpub.net/11355887/viewspace-974948/
我这个迭代公式是同除x^2的,循环有点重复,就十分钟写的懒得改了。
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
double fun(double x);
void AitkenIterative(double x);
int main()
{
double x0=1.5;
AitkenIterative(x0);
return 0;
}
double fun(double x)
{
return 1 + 1.0/pow(x,2); // φ(x)=1+1/x^2
}
/////////
int i=0;
void AitkenIterative(double x)
{
cout<<"x"<< i << " : "<< x << endl;
double y1 = fun(x);
double z1 = fun(y1);
cout<<"y"<< i+1 << " : "<< y1 << endl;
cout<<"z"<< i+1 << " : "<< z1 << endl;
double x1 = ( x*z1 - y1*y1 ) / ( x-2*y1+z1 );
cout<<"x"<< i+1 << " : "<< x1 << endl;
//---------------------------------------------
double y2 = fun(x1);
double z2 = fun(y2);
cout<<"y"<< i+2 << " : "<< y2 << endl;
cout<<"z"<< i+2 << " : "<< z2 << endl;
double x2 = ( x1*z2 - y2*y2 ) / ( x1-2*y2+z2 );
cout <<"x"<< i+2 << " : "<< x2 << endl;
double cha= fabs( x2-x1 );
cout <<"x"<< i+2 << "-" <<"x"<< i+1 << " : "<< cha << endl;
if( i<5 && cha>0.0001 ){
i++;
cout <<"---------------"<<endl;
AitkenIterative(x1);
}
else return ;
}
可能有错,欢迎指正交流