松弛迭代法求根C++语言

#include
#include
#include
#include "fstream"
#define esp 0.5e-8 
using namespace std;
class  SLACK
{
private:
 int time;     //迭代次数 
 double svalue;    //迭代初值  
public: 
 double aa[20];    //用于存放每次迭代的xk;
 double bb[20];    //用于存放每次迭代的误差 f;
 double fun(double xk);  // 需要迭代的函数 
 double Itformat(double xk); //函数的迭代格式  
 void getvalue();   //从文本中读值
 double slack();    //计算
 void  show();    //输出
};
double SLACK::fun(double xk)
{
 double f;
 f=(xk*xk-2*log(xk)-5);     
 return f;
}
double SLACK::Itformat(double xk)
{
 xk=-xk/(xk*sqrt(2*log(xk)+5)-1)+xk*(2*log(xk)+5)/(xk*sqrt(2*log(xk)+5)-1);
 return xk;
}
void SLACK::getvalue()
{
 double a[2]; 
 ifstream infile("in.txt",ios::in);
 if(!infile)
 {
  cerr<<"In file open error!"<<endl;
  exit(1);
 }
 for(int i=0;i<2;i++)
  infile>>a[i];
 SLACK::svalue=a[0]; 
 SLACK::time=a[1];
 infile.close();  
 
}
double SLACK::slack()
{ 
 
 int counter=0;  //迭代次数计数
 double xk=0;
 double f;  
 xk=SLACK::svalue;  
 do
 { 
  xk=SLACK::Itformat(xk);  
  f=SLACK::fun(xk);
  aa[counter]=xk; 
  bb[counter]=f;
  counter++;   
 }
 while (counteresp);
 SLACK::time=counter;
 aa[counter++]='\n';
 bb[counter++]='\n';
 return 0;
 
}
void SLACK::show()
{
 ofstream outfile("out.txt",ios::out); 
 for(int i=0;i
 {
  cout<<fixed<<setprecision(15);    //控制输出精度
  cout<<"第"<<i+1<<"次迭代结果:"<<aa[i]<<endl;
  cout<<"第"<<i+1<<"次迭代误差:"<<bb[i]<<endl;
  cout<<"-------------------------------------------------"<<endl;
  outfile<<fixed<<setprecision(15);  //控制输出精度
  outfile<<"第"<<i+1<<"次迭代结果:"<<aa[i]<<endl;
  outfile<<"第"<<i+1<<"次迭代误差:"<<bb[i]<<endl;
  outfile<<"-------------------------------------------------"<<endl;
  
 }
 outfile.close(); 
}
int  main()
{ 
 
 SLACK  std;
 std.getvalue();
 std.slack();
 std.show();
 return 0; 
}

猜你喜欢

转载自blog.csdn.net/qq_28114083/article/details/80733924
今日推荐