#include #include #include #include "fstream" #define esp 0.5e-8 using namespace std; class SLACK { private: int time; //迭代次数 double left; //迭代初值 double right; int flag; public: double aa[2][20]; //用于存放每次迭代的xk; double bb[2][20]; //用于存放每次迭代的误差 f; double fun(double xk); // 需要迭代的函数 double Itformat(double xk); //函数的迭代格式 void getvalue(); //从文本中读值 double slack(); //计算 void show(); //输出 double fun1(double xk); }; double SLACK::fun(double xk) { double f; f = xk*xk*xk*xk-4*xk*xk+4; return f; } double SLACK::fun1(double xk) { double f; f = 4*xk*xk*xk-8*xk; return f; } double SLACK::Itformat(double xk)// { double x1; x1=xk-1.0*fun(xk)/fun1(xk); return (x1); } void SLACK::getvalue() { double a[3]; ifstream infile("in.txt",ios::in); if(!infile) { cerr<<"In file open error!"<<endl; exit(1); } for(int i=0;i<3;i++) infile>>a[i]; SLACK::left=a[0]; SLACK::right=a[1]; SLACK::time=a[2]; infile.close(); } double SLACK::slack() { double p; int counter=0; double xk=0; double f; xk=SLACK::left; /////// 判断左短点附近的值 do { xk=Itformat(xk); f=fun(xk); aa[0][counter]=xk; bb[0][counter]=f; counter++; } while (counteresp); SLACK::time=counter; aa[0][counter++]='\n'; bb[0][counter++]='\n'; counter=0; xk=SLACK::right; //////////////// 判读右端点附近的值 do { xk=Itformat(xk); f=fun(xk); aa[1][counter]=xk; bb[1][counter]=f; counter++; } while (counteresp); SLACK::time=counter; aa[1][counter++]='\n'; bb[1][counter++]='\n'; /////////////////////判断两边近似解是否一样//////////////////////// p=fabs(aa[0][counter]-aa[1][counter]); if(p<0.001) SLACK::flag=1; ///两端点附近的解一样 else SLACK::flag=0; // 相反 return 0; } void SLACK::show() { ofstream outfile("out.txt",ios::out); if(SLACK::flag==1) { cout<<"有两个解"<<endl; outfile<<"有两个解"<<endl; for(int j=0;j<2;j++) for(int i=0;i { cout<<fixed<<setprecision(15); //控制输出精度 cout<<"第"<<i+1<<"次迭代结果:"<<aa[j][i]<<endl; cout<<"第"<<i+1<<"次迭代误差:"<<bb[j][i]<<endl; cout<<"-------------------------------------------------"<<endl; outfile<<fixed<<setprecision(15); //控制输出精度 outfile<<"第"<<i+1<<"次迭代结果:"<<aa[j][i]<<endl; outfile<<"第"<<i+1<<"次迭代误差:"<<bb[j][i]<<endl; outfile<<"-------------------------------------------------"<<endl; } cout<<"******************************************************"<<endl; outfile<<"******************************************************"<<endl; } else if(SLACK::flag==0) { cout<<"有一个解"<<endl; outfile<<"有一个解"<<endl; for(int i=0;i { cout<<fixed<<setprecision(15); //控制输出精度 cout<<"第"<<i+1<<"次迭代结果:"<<aa[0][i]<<endl; cout<<"第"<<i+1<<"次迭代误差:"<<bb[0][i]<<endl; cout<<"-------------------------------------------------"<<endl; outfile<<fixed<<setprecision(15); //控制输出精度 outfile<<"第"<<i+1<<"次迭代结果:"<<aa[0][i]<<endl; outfile<<"第"<<i+1<<"次迭代误差:"<<bb[0][i]<<endl; outfile<<"-------------------------------------------------"<<endl; } } else ; outfile.close(); } int main() { SLACK std; std.getvalue(); std.slack(); std.show(); return 0; }
牛顿迭代法求方程解(单重根情形) c++
猜你喜欢
转载自blog.csdn.net/qq_28114083/article/details/80733847
今日推荐
周排行