Advertisement
cd62131

solve with LU decomposition

Dec 14th, 2018
2,537
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.31 KB | None | 0 0
  1. #include <stdio.h>
  2. #define N (4)
  3. int main(void) {
  4.   double a[N][N] = {{4., -6., -10., -2.},
  5.                     {-6., 8., 21., -1.},
  6.                     {-10., 21., -20., 23.},
  7.                     {-2., -1., 23., -18.}};
  8.   double b[N] = {-46., 69., 64., -7.};
  9.   double L[N][N] = {
  10.       {0., 0., 0., 0.}, {0., 0., 0., 0.}, {0., 0., 0., 0.}, {0., 0., 0., 0.}};
  11.   double U[N][N] = {
  12.       {1., 0., 0., 0.}, {0., 1., 0., 0.}, {0., 0., 1., 0.}, {0., 0., 0., 1.}};
  13.   for (int k = 0; k < N; ++k) {
  14.     for (int i = k; i < N; ++i) {
  15.       double s = 0.;
  16.       for (int j = 0; j < k; ++j) {
  17.         s += L[i][j] * U[j][k];
  18.       }
  19.       L[i][k] = a[i][k] - s;
  20.     }
  21.     for (int j = k + 1; j < N; ++j) {
  22.       double s = 0.;
  23.       for (int i = 0; i < k; ++i) {
  24.         s += L[k][i] * U[i][j];
  25.       }
  26.       U[k][j] = (a[k][j] - s) / L[k][k];
  27.     }
  28.   }
  29.   double x[N], y[N];
  30.   for (int i = 0; i < N; ++i) {
  31.     double s = 0.;
  32.     for (int j = 0; j < i; ++j) {
  33.       s += L[i][j] * y[j];
  34.     }
  35.     y[i] = (b[i] - s) / L[i][i];
  36.   }
  37.   for (int i = N - 1; 0 <= i; --i) {
  38.     double s = 0.;
  39.     for (int j = i + 1; j < N; ++j) {
  40.       s += U[i][j] * x[j];
  41.     }
  42.     x[i] = y[i] - s;
  43.   }
  44.   printf("x = {");
  45.   for (int i = 0; i < N; ++i) {
  46.     printf("%s%f", (i == 0 ? "" : ", "), x[i]);
  47.   }
  48.   puts("}");
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement