[算法][雅可比迭代解方程组]

 1 #include<iostream>
 2 #include<cmath>
 3 using namespace std;
 4 #define maxn 50
 5 int n;//维数
 6 double a[maxn][maxn];//系数矩阵
 7 double b[maxn];//b向量
 8 double kc=0.000001;//精度控制常数
 9 double x[maxn];//x向量
10 double y[maxn];
11 double e;
12 int N0;//最大迭代次数
13 //e=||x-(k+1)-x(k)||.inf.;当e<kc时计算终止;N0为最大迭代次数;
14 //t用于暂时存放Xi的原值,以便计算Xi-(k)-Xi(k-1)
15 int i,j,k;
16 bool read(){
17     cout<<"|----------------------------------------|\n";
18     cout<<"请输入矩阵规模n:= ";
19     cin>>n;
20     cout<<"请输入系数矩阵A:= \n";
21     for(i=1;i<=n;i++)//输入a[][]
22         for(j=1;j<=n;j++)
23             cin>>a[i][j];
24     cout<<"请输入b向量b:= \n";
25     for(i=1;i<=n;i++)cin>>b[i];//输入b[]
26     cout<<"请输入x向量的初始值x:= \n";
27     for(i=1;i<=n;i++)cin>>x[i];//输入x[]初始值
28     cout<<"请输入估计最大迭代次数N0:= \n";
29     cin>>N0;
30     return 1;
31 }
32 int main(){
33     while(read()){
34         for(k=1;k<=N0;k++){
35             e=-1;
36             for(i=1;i<=n;i++){
37                 y[i]=b[i];
38                 for(j=1;j<=n;j++)if(i!=j){
39                     y[i]-=a[i][j]*x[j];
40                 }
41                 y[i]/=a[i][i];
42                 if(fabs(x[i]-y[i])>e)e=fabs(x[i]-y[i]);    
43             }if(e<kc){//输出
44                 cout<<"|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|\n";
45                 cout<<"最大迭代次数 k = "<<k<<'\n';
46                 for(i=1;i<=n;i++)cout<<"x["<<i<<"]="<<y[i]<<'\n';
47                 goto END;
48             }else{
49                 for(i=1;i<=n;i++)x[i]=y[i];    
50             }
51         }    
52         cout<<"|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^|\n";
53         cout<<"失败\n";
54         END:;
55         cout<<"|----------------------------------------|\n\n";
56     }return 0;
57 }
58 /*
59 6
60 
61 4 -1 0 -1 0 0
62 -1 4 -1 0 -1 0
63 0 -1 4 -1 0 -1
64 -1 0 -1 4 -1 0
65 0 -1 0 -1 4 -1
66 0 0 -1 0 -1 4
67 
68 0 5 -2 5 -2 6
69 
70 0 0 0 0 0 0
71 
72 50
73 */

 

 

 

 

posted @ 2014-04-17 14:13  beautifulzzzz  阅读(2145)  评论(0编辑  收藏  举报