Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Nie używaj zmiennych globalnych, ani dyrektyw #define
- // Utrudniają one zrobienie ogólnych funkcji.
- #include <cmath>
- #include <cstdio>
- #include <cstdlib>
- double ** matrix(int n); // alokuje macierz nxn
- void free_matrix(double **A, int n); // zwalnia macierz nxn
- void transpose(double **A, int n); // Transponuje macierz nxn
- void print_matrix(double **A, int n); // Wypisuje macierz nxn na ekran
- // Liczy wyznacznik macierzy nxn. Nie powinien zmieniac macierzy A.
- double det(double **A, int n);
- // Kopiuje z A do B wszystkie elementy oprócz elementów z wiersza r i kolumny k
- void copy_without(double **B, double **A, int r, int k, int n);
- // Odwraca macierz nxn
- void inverse(double **A, int n) {
- static const double eps = 1e-10;
- double detA = det(A, n);
- if (fabs(detA) < eps) {
- printf("Macierz jest osobliwa!\n");
- return;
- }
- double **B = matrix(n-1); // Macierz pomocnicza.
- double **D = matrix(n); // Macierz dopełnień.
- // W każdej iteracji będziemy rozwijać wzór na elemencie A[r][k]
- for (int r = 0; r < n; r++) {
- for (int k = 0; k < n; k++) {
- copy_without(B, A, r, k, n);
- int sign = ((r+k)%2 == 0) ? 1 : -1;
- D[r][k] = sign * det(B, n-1);
- }
- }
- transpose(D, n);
- for (int r = 0; r < n; r++) {
- for (int k = 0; k < n; k++) {
- A[r][k] = D[r][k] / detA;
- }
- }
- free_matrix(D, n);
- free_matrix(B, n-1);
- }
- int main(void) {
- printf("dla A:\n");
- double **A = matrix(2);
- A[0][0] = 2; A[0][1] = 1;
- A[1][0] = 5; A[1][1] = 3;
- print_matrix(A, 2);
- inverse(A, 2);
- print_matrix(A, 2);
- free_matrix(A, 2);
- /*
- dla A:
- 2 1
- 5 3
- 3 -1
- -5 2
- */
- printf("dla B:\n");
- srand(4);
- double **B = matrix(4);
- for (int i = 0; i < 4; i++) {
- for (int j = 0; j < 4; j++) {
- B[i][j] = (rand() % 10);
- }
- }
- print_matrix(B, 4);
- inverse(B, 4);
- print_matrix(B, 4);
- free_matrix(B, 4);
- /*
- dla B:
- 1 5 9 6
- 5 4 5 6
- 0 0 1 7
- 2 0 2 7
- -0.0894569 0.111821 -0.284345 0.265176
- -0.0734824 0.341853 0.587859 -0.817891
- 0 0 -0.43131 0.469649
- 0 0 0.204473 -0.0670927
- */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment