#include #include #include using namespace std; #define f(x) (1/x) class ROMBERG { public: double a[4]; }; double Romberg(double aa, double bb ,double epsilon, double MAXREPT ) { ofstream outfile("out.txt",ios::out); int m, n; n=2^m ; double h, x; double s, q; double ep; double *y = new double[MAXREPT]; double p; h = bb - aa; y[0] = h*(f(aa) + f(bb))/2.0; m = 1; n = 1; ep = epsilon + 1.0; if(MAXREPT<=1) { cout<<"迭代次数必须大于1" <<endl; } else { if(MAXREPT<6) { cout<<"没有达到最大迭代次数" <<endl; } while ((ep>= epsilon) && (m < MAXREPT)) { p = 0.0; for (int i=0; i { x = aa + (i+0.5)*h; p = p + f(x); } p = (y[0] + h*p)/2.0;//求T2n = 1/2(Tn+Hn),用p指示 cout<<"第"<<i<<"次迭代结果为:"<<p<<endl; outfile<<"第"<<i<<"次迭代结果为:"<<p<<endl; //求第m行元素,根据Romberg计算表本行的前一个元素(p指示), //和上一行左上角元素(y[k-1]指示)求得. s = 1.0; for (int k=1; k<=m; k++) { s = 4.0*s; q = (s*p - y[k-1])/(s - 1.0); y[k-1] = p; p = q; } ep = fabs(q - y[m-1]); m = m + 1; y[m-1] = q; n = n + n; h = h/2.0; } outfile<<q<<endl; outfile<<"积分结果:"<<q<<endl; } return (q); } int main() { ROMBERG xl; double a,b; ifstream infile("in.txt",ios::in); if(!infile) { cerr<<"In file open error!"<<endl; exit(1); } for(int i=0;i<4;i++) infile>>xl.a[i]; a=xl.a[0];b=xl.a[1]; cout<<"积分结果:"<<Romberg(a, b,xl.a[2],xl.a[3])<<endl; // system("pause"); return 0; }
Romberg积分法求解方程根 c++语言
猜你喜欢
转载自blog.csdn.net/qq_28114083/article/details/80733936
今日推荐
周排行