雅可比迭代法
1 // 如下程序中的for语句未修改前为:for(j=0;j!=i&&j<6;j++) ,输出结果为5次迭代而不是正确的27次,j!=i放在for语句中则会减少迭代次数从而产生误解 2 #include<iostream> 3 4 #include<cmath> 5 6 using namespace std; 7 double fanshu(double x[], double y[], int n) 8 { 9 double sums = 0; 10 for(int p = 0; p < n; p++) 11 sums += (y[p] - x[p]) * (y[p] - x[p]); 12 return sqrt(sums); 13 } 14 void main() 15 { 16 double A[6][6] = {4, -1, 0, -1, 0, 0, -1, 4, -1, 0, -1, 0, 0, -1, 4, -1, 0, -1, -1, 0, -1, 4, -1, 0, 0, -1, 0, -1, 4, -1, 0, 0, -1, 0, -1, 4}; 17 double b[6] = {0, 5, -2, 5, -2, 6}; 18 double x[6] = {0, 0, 0, 0, 0, 0}; //设置X初值全为0; 19 double y[6] = {0, 0, 0, 0, 0, 0}; 20 int N = 50; 21 int k, i, j, l; 22 double e; 23 for(k = 0; k < N; k++) 24 { 25 for(i = 0; i < 6; i++) 26 { 27 double sum = 0; 28 for(j = 0; j < 6; j++) 29 if(j != i) 30 { 31 sum += A[i][j] * x[j]; 32 } 33 y[i] = (b[i] - sum) / A[i][i]; 34 } 35 e = fanshu(x, y, 6); 36 if(e < 0.0001) 37 { 38 break; 39 } 40 for(l = 0; l < 6; l++) 41 x[l] = y[l]; 42 } 43 cout << "迭代次数为:" << k << endl; 44 cout << "结果为: "; 45 for(int h = 0; h < 6; h++) 46 cout << y[h] << " "; 47 cout << endl; 48 }