c7-2.cpp
资源名称:数值分析课程设计.zip [点击查看]
上传用户:zhdd911129
上传日期:2007-05-11
资源大小:722k
文件大小:1k
源码类别:
matlab例程
开发平台:
Matlab
- //C7
- //Solve a linear system,using Jacobi Iteration
- const int N=4;
- #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 JI(double a[][N],double b[],double x0[],double tol,int max,int n)
- {
- double x1[N];
- int k,i,j;
- for (i=0;i<n;i++)
- {
- x1[i]=0;
- }
- 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]*x0[j];
- }
- }
- x1[i]=((-1)*x1[i]+b[i])/a[i][i];
- }
- if(ReachTOL(x0,x1,tol,n))
- {
- for (i=0;i<n;i++)
- {
- cout<<"x"<<i<<" is: "<<x1[i]<<endl;
- }
- cout<<endl;
- return;
- }
- for (i=0;i<n;i++)
- {
- x0[i]=x1[i];
- x1[i]=0;
- }
- }
- cout<<"Exceed the maximium iteration time"<<endl;
- for (i=0;i<n;i++)
- {
- cout<<"x"<<i<<" is: "<<x1[i];
- }
- cout<<endl;
- }
- void main(void)
- {
- double a[N][N]={{78,-2,-12,-14}, //为克服C语言中输入浮点数的漏洞,这里采用先输大数后输小数的方式
- {-2,86,-4,6},
- {-12,-4,72,-8},
- {-14,6,-8,74}};
- double b[N]={76,8,112,68};
- double x0[N]={0,0,0,0};
- double tol=1e-2;
- int max=100,i,j;
- for(i=0;i<N;i++)
- {
- for(j=0;j<N;j++)
- {
- a[i][j]/=100;
- }
- }
- for (i=0;i<N;i++)
- {
- b[i]/=100;
- }
- JI(a,b,x0,tol,max,N);
- }