[ create a new paste ] login | about

Link: http://codepad.org/rqMERblh    [ raw code | output | fork ]

C, pasted on Nov 24:
#include <stdio.h>
#include <math.h>
/* #include <conio.h> */

/* #define CASE1 */
#define CASE2
static double a[3][4] = {
#if defined(CASE1)
  { 2.0, 1.0, 3.0, 13.0 },
  { 1.0, 3.0, 2.0, 13.0 },
  { 3.0, 2.0, 1.0, 10.0 }
#endif
#if defined(CASE2)
  { 0.0, 0.0, 1.0, 13.0 },
  { 1.0, 0.0, 0.0, 13.0 },
  { 0.0, 1.0, 0.0, 10.0 }
#endif
};

void swap(double *a, double *b)
{
  double tmp;
  tmp = *a;
  *a = *b;
  *b = tmp;
}

int main()
{
  int n = 3;
  int i, j, k;
  int m, l;
  double eps = 0.00001;
  double piv, del, max;

  for (i = 0; i < n; i++) {
    l = i;
    max = a[i][i];
    for (m = i; m < 3; m++) {
      if (max < a[m][i]) {
        max = a[m][i];
        l = m;
      }
    }
    for (m = 0; m < n + 1; m++) {
      swap(&a[i][m], &a[l][m]);
    }

    piv = a[i][i];
    if (fabs(piv) < eps) {
      printf("Error: ピボット数が誤差限界を超えたので処理を中止します。");
      return -1;
    }
    for (j = 0; j < n + 1; j++) {
      a[i][j] = a[i][j] / piv;
    }

    for (k = 0; k < n; k++) {
      del = a[k][i];
      for (j = 0; j < n + 1; j++) {
        if (k != i) {
          a[k][j] = a[k][j] - del * a[i][j]; 
        }
      }
    }
  }
  for (i = 0; i < n; i++) { 
    printf("x[%d] = %lf\n", i, a[i][n]);
  }
  return 0;
}
/* end */


Output:
1
2
3
x[0] = 13.000000
x[1] = 10.000000
x[2] = 13.000000


Create a new paste based on this one


Comments: