雅可比迭代法Jacobi_解线性方程组的迭代法

雅可比迭代法Jacobi_解线性方程组的迭代法

标签:计算方法实验

#include 
#include 

#define maxn 3

int main()
{
    double a[maxn][maxn + 1], y[maxn], x[maxn] = {0};
    double eps = 1e-9;
    int n, k, kmax = 100;

    freopen("gauss.txt", "r", stdin);
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
        for(int j = 0; j < n + 1; j++)
            scanf("%lf", &a[i][j]);
    //for(int i = 0; i < n; i++)
    //{
        //for(int j = 0; j < n + 1; j++)  printf("%-15f", a[i][j]);
        //printf("\n");
    //}

    for(k = 0; k < kmax; k++)
    {
         double norm = 0;

         for(int i = 0; i < n; i++)
         {
             double sum = 0;
             for(int j = 0; j < n; j++)  if(j != i)  sum += a[i][j] * x[j];  ///
             y[i] = (a[i][n] - sum) / a[i][i];  //n
             if(fabs(y[i] - x[i]) > norm) norm = fabs(y[i] - x[i]);  //norm计算范数
         }
         printf("\nk = %2d  x =  ", k + 1);
         for(int i = 0; i < n; i++)  printf("%-15f", y[i]);
         for(int i = 0; i < n; i++)  x[i] = y[i];
         if(norm < eps)  break;
    }
    if(k < kmax)
    {
        printf("\n\nk = %d\n", k + 1);
        for(int i = 0; i < n; i++)  printf("x%d = %-15f\n", i + 1, x[i]);
    }
    else  printf("\n\nfailed\n");

    return 0;
}

数据文件
雅可比迭代法Jacobi_解线性方程组的迭代法_第1张图片
实验结果
雅可比迭代法Jacobi_解线性方程组的迭代法_第2张图片

你可能感兴趣的:(计算方法实验)