<>//松弛迭代(SOR)方法</P><>#include <vector>
#include <math.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h></P><>using namespace std;</P><P>ofstream out("out.txt");</P><P>double operator * (vector<double> a,vector<double> b)
{
double data=0;
if(a.size()==b.size())
{
vector<double> :: iterator it1=a.begin();
vector<double> :: iterator it2=b.begin();
for(;it1!=a.end();++it1,++it2)
{
data+=((*it2)*(*it1));
}
}
return data;
}</P><P>double Delta(vector<double> a,vector<double> b)
{
double data=0;
if(a.size()==b.size())
{
vector<double> :: iterator it1=a.begin();
vector<double> :: iterator it2=b.begin();
for(;(it1!=a.end())&&(it2!=b.end());++it1,++it2)
{
if(fabs((*it1)-(*it2))>data)
{
data=fabs((*it1)-(*it2));
}
}
}
return data;
}
vector<double> GS(vector<vector<double> > A,vector<double> B,vector<vector<double> > D,vector<vector<double> > L,double delta,double w)
{
vector<double> x1(B.size(),0);
vector<double> x2(B.size(),0);
do
{
x1=x2;
for(int i=0;i<(int)x2.size();++i)
{
double xx=L*x2;
xx+=D*x1;
x2=(B-xx)/A;
}
for(int i=0;i<(int)x2.size();++i)
{
x2=(1-w)*x1+w*x2;
}
}while(Delta(x1,x2)>delta);
return x1;
}</P><P>void Print(vector<double> a)
{
vector<double> :: iterator it=a.begin();
for(;it!=a.end();++it)
{
cout<<(*it)<<"\t";
out<<(*it)<<"\t";
}
cout<<endl;
out<<endl;
}</P><P>void Print(vector<vector<double> > A)
{
for(int i=0;i<A.size();++i)
{
Print(A);
}
}
int main()
{
cout<<"Define the dimension of the matrix:"<<endl;
int num;
cin>>num;
vector<vector<double> > A(num);
vector<double> B;
for(int i=0;i<num;++i)
{
double bb=0;
for(int j=0;j<num;++j)
{
{
A.push_back(1/((double)i+(double)j+1));
bb+=(1/((double)i+(double)j+1));
}
}
B.push_back(bb);
}
cout<<"Input the delta:"<<endl;
double delta;
cin>>delta;
cout<<"Input the SOR coefficient:"<<endl;
double w;
cin>>w;
cout<<"The Result is:"<<endl;
vector<vector<double> > D;
vector<vector<double> > L;
for(int i=0;i<(int)A.size();++i)
{
vector<double> z(A.size(),0);
vector<double> y(A.size(),0);
for(int j=0;j<(int)A.size();++j)
{
if(j<i)
{
z[j]=A[j];
}
else if(j>i)
{
y[j]=A[j];
}
}
D.push_back(y);
L.push_back(z);
}
Print(GS(A,B,D,L,delta,w));
system("PAUSE");
}
</P> |