高斯赛德尔方法

时间:2015-04-02 20:56:19

标签: java matrix linear-algebra gaussian

我写了一个高斯 - 赛德尔方法来计算矩阵A的未知x值。如果行列式包含非零,那么在线的其他方法似乎首先检查,但其他算法,包括我的教授的笔记,没有验证检查。

所以我只是按照我教授现在给出的算法,我认为第一个xNew是正确的,因为我在我的计算器上验证了它,但我的其他x值没有更新,有人能看出原因吗?

public static void gaussSeidel(double[][] A, double[] b){
int count = 0;
boolean stop = false;

do{
  double[] xNew = new double[b.length]; // x2 = 0, x3 = 0,
  double[] xOld = new double[b.length]; 

  for(int i = 0; i < A.length; i++){ 
    double sum = 0.0;
    double sum1 = 0.0;
    for(int j = 0; j < A.length; j++){

      if( j != i)
        sum += (A[i][j]*xOld[j]);

     sum1 += (A[i][j]*xNew[j]);
    }

    xNew[i] = (b[i] - sum - sum1)*(1/A[i][i]);
    System.out.println("X_" + (i+1) + ": " + xNew[i]);
    System.out.println("Error is: " + Math.abs((xNew[i] - xOld[i])));
    System.out.println("");
    count++;

    if(Math.abs(xNew[i] - xOld[i]) > EPSILON){
      xNew[i] = xOld[i];
      }

    else{
      stop = true;}   
  }
}while( !stop && count <= MAX_ITERATIONS);
}

我的矩阵:
      double[][] a = {{12,-2,1,0,0,0,0,0,0,0,0}, {-2,12,2,1,0,0,0,0,0,0,0}, {1,-2,12,-2,1,0,0,0,0,0,0}, {0,1,-2,12,-2,1,0,0,0,0,0}, {0,0,1,-2,12,2,1,0,0,0,0}, {0,0,0,1,-2,12,-2,1,0,0,0}, {0,0,0,0,1,-2,12,-2,1,0,0},{0,0,0,0,0,1,-2,12,-2,1,0}, {0,0,0,0,0,0,1,-2,12,-2,0},{0,0,0,0,0,0,0,1,-2,12,0}};

我的b值:

double[] b = {13.97, 5.93, -6.02, 8.32, -23.75, 28.45, -8.9, -10.5, 10.34, -38.74};

1 个答案:

答案 0 :(得分:0)

每次循环时,您都会反复创建以下数组:

  double[] xNew = new double[b.length]; // x2 = 0, x3 = 0,
  double[] xOld = new double[b.length]; 

当然,您正在丢失在前一循环中计算的值。我认为你只需要创建一次,所以在你的循环之外如下:

public static void gaussSeidel(double[][] A, double[] b){
int count = 0;
boolean stop = false;

double[] xNew = new double[b.length]; // x2 = 0, x3 = 0,
double[] xOld = new double[b.length]; 

do{

  for(int i = 0; i < A.length; i++){ 
    double sum = 0.0;
    double sum1 = 0.0;
    for(int j = 0; j < A.length; j++){

      if( j != i)
        sum += (A[i][j]*xOld[j]);

     sum1 += (A[i][j]*xNew[j]);
    }

    xNew[i] = (b[i] - sum - sum1)*(1/A[i][i]);
    System.out.println("X_" + (i+1) + ": " + xNew[i]);
    System.out.println("Error is: " + Math.abs((xNew[i] - xOld[i])));
    System.out.println("");
    count++;

    if(Math.abs(xNew[i] - xOld[i]) > EPSILON){
      xNew[i] = xOld[i];
      }

    else{
      stop = true;}   
  }
}while( !stop && count <= MAX_ITERATIONS);
}