NyanCoder

Jacobi.c

Apr 18th, 2022 (edited)
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. #include "stdlib.h"
  2. #include "stdio.h"
  3. #include "math.h"
  4.  
  5. float* Jacobi(int size, float** A, float eps)
  6. {
  7.     float* x = (float*)malloc(sizeof(float) * size);
  8.     float* tempX = (float*)malloc(sizeof(float) * size);
  9.     for (int i = 0; i < size; i++)
  10.         x[i] = tempX[i] = 0;
  11.     float norm;
  12.  
  13.     do {
  14.         for (int i = 0; i < size; i++) {
  15.             tempX[i] = A[i][size];
  16.             for (int g = 0; g < size; g++) {
  17.                 if (i != g)
  18.                     tempX[i] -= A[i][g] * x[g];
  19.             }
  20.             tempX[i] /= A[i][i];
  21.         }
  22.         norm = fabs(x[0] - tempX[0]);
  23.         for (int h = 0; h < size; h++) {
  24.             if (fabs(x[h] - tempX[h]) > norm)
  25.                 norm = fabs(x[h] - tempX[h]);
  26.             x[h] = tempX[h];
  27.         }
  28.     } while (norm > eps);
  29.     free(tempX);
  30.  
  31.     return x;
  32. }
  33.  
  34. int main(int argc, char** argv)
  35. {
  36.     int size = 0;
  37.     do {
  38.         printf("Введите порядок матрицы:\n");
  39.         scanf("%d", &size);
  40.     } while (size < 1);
  41.  
  42.     float** a = (float**)malloc(sizeof(void*) * size);
  43.  
  44.     printf("Введите матрицу:\n");
  45.     for (int i = 0; i < size; i++)
  46.     {
  47.         a[i] = (float*)malloc(sizeof(float) * (size + 1));
  48.         for (int j = 0; j <= size; j++)
  49.             scanf("%f", &a[i][j]);
  50.     }
  51.     printf("\n");
  52.  
  53.     float* x = Jacobi(size, a, 0.001f);
  54.     for (int i = 0; i < size; i++)
  55.     {
  56.         printf("x[%d]=%f\n", i + 1, x[i]);
  57.     }
  58.  
  59.     return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment