informaticage

Gauss Back substitution

Mar 14th, 2021 (edited)
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <iostream>
  2. #define DIMENSIONE 50
  3.  
  4. double *backSub(double mat[DIMENSIONE][DIMENSIONE + 1], int grado) {
  5.   double *soluzioni = new double[grado];
  6.   // Sostituiamo partendo da x(n) = k
  7.   for (int i = grado - 1; i >= 0; i--) {
  8.     soluzioni[i] = mat[i][grado];
  9.     // Assumiamo una triangolare superiore
  10.     for (int j = i + 1; j < grado; j++) {
  11.       soluzioni[i] -= mat[i][j] * soluzioni[j];
  12.     }
  13.     // Divisione per i coefficienti
  14.     soluzioni[i] = soluzioni[i] / mat[i][i];
  15.   }
  16.   return soluzioni;
  17. }
  18.  
  19. int main() {
  20.   using namespace std;
  21.   // Dichiriamo una DIMENSIONE x DIMENSIONE
  22.   double M[DIMENSIONE][DIMENSIONE + 1];
  23.   int grado;
  24.   cout << "Inserire il grado del sistema: ";
  25.   cin >> grado;
  26.  
  27.   if (grado > DIMENSIONE - 1) {
  28.     cout << "La dimensione della matrice e' troppo grande per essere calcolata"
  29.          << endl;
  30.     return 0;
  31.   }
  32.  
  33.   // La carichiamo
  34.   for (int i = 0; i < grado; i++) {
  35.     for (int j = 0; j < grado + 1; j++) {
  36.       cout << "Agg(" << i + 1 << "," << j + 1 << "): ";
  37.       cin >> M[i][j];
  38.     }
  39.   }
  40.  
  41.   double *soluzioni = backSub(M, grado);
  42.   cout << "Vettore delle soluzioni: " << endl;
  43.   for (int i = 0; i < grado; i++) {
  44.     cout << "X" << i + 1 << ": " << soluzioni[i] << endl;
  45.   }
  46.  
  47.   return 0;
  48. }
Add Comment
Please, Sign In to add comment