c8.cpp
资源名称:数值分析课程设计.zip [点击查看]
上传用户:zhdd911129
上传日期:2007-05-11
资源大小:722k
文件大小:2k
源码类别:
matlab例程
开发平台:
Matlab
- //C8.cpp
- //Solve a linear system,using G-S Iteration
- const int N=3;
- #include<iostream.h>
- int ReachTOL(double x1[],double x2[],double tol,int n)
- {
- int i;
- double error=0;
- for (i=0;i<n;i++)
- {
- error+=(x1[i]-x2[i])*(x1[i]-x2[i]);
- }
- if(error<tol)
- return 1;
- else
- return 0;
- }
- void GSI(double a[][N],double b[],double x0[],double tol,int max,int n)
- {
- double x1[N],x00[N];
- int k,i,j;
- for (i=0;i<n;i++) //Initialazation
- {
- x1[i]=0;
- x00[i]=x0[i];
- }
- for (k=0;k<max;k++)
- {
- for (i=0;i<n;i++)
- {
- for (j=0;j<n;j++)
- {
- if(j!=i)
- {
- x1[i]+=a[i][j]*x00[j];
- }
- }
- x1[i]=((-1)*x1[i]+b[i])/a[i][i];
- if(i<n-1)
- x00[i]=x1[i];
- }
- if(ReachTOL(x00,x1,tol,n))
- {
- for (i=0;i<n;i++)
- {
- cout<<"x"<<i<<" is: "<<x1[i]<<endl;
- }
- cout<<x1[0]*(-1)+6*x1[1]-1*x1[2];
- cout<<endl;
- cout<<"Has iterated "<<k<<" times."<<endl;
- return;
- }
- x00[n-1]=x1[n-1];
- for (i=0;i<n;i++)
- {
- x1[i]=0;
- }
- }
- cout<<"Exceed the maximium iteration time"<<endl;
- for (i=0;i<n;i++)
- {
- cout<<"x"<<i<<" is: "<<x1[i]<<endl;
- }
- cout<<endl;
- }
- void main(void)
- {
- double a[N][N]={6,-1,-1,
- -1,6,-1,
- -1,-1,6};
- double b[N]={11.33,32,42};
- double x0[N]={0,0,0};
- double tol=1e-6;
- int max=100,i,j;
- for(i=0;i<N;i++)
- {
- for(j=0;j<N;j++)
- {
- a[i][j]/=100; //why divide 100?
- }
- }
- for (i=0;i<N;i++)
- {
- b[i]/=100;
- }
- GSI(a,b,x0,tol,max,N);
- cin>>i;
- }
- //Result:reach the precision of 1e-4,with iteration of 5 times
- //x0 is: 4.66597;x1 is: 7.61888;x2 is: 9.04747
- //从后面的比较可以看出GS的确比Jacobi占优