Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #define MAX_SIZE 100
- typedef double (*Matrix)[MAX_SIZE];
- double norm(Matrix A, int n);
- double determinant(Matrix A, int n);
- double** inverse_matrix(Matrix A, int n);
- double norm(Matrix A, int n) {
- double max_norm = 0.0;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- double abs_val = fabs(A[i][j]);
- if (abs_val > max_norm) {
- max_norm = abs_val;
- }
- }
- }
- return max_norm;
- }
- double** inverse_matrix(Matrix A, int n) {
- double** adjoint = malloc(n * sizeof(double*));
- for (int i = 0; i < n; i++) {
- adjoint[i] = malloc(n * sizeof(double));
- }
- // Вычисление алгебраических дополнений
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- int sub_n = n - 1;
- double (*sub_matrix)[sub_n] = malloc(sub_n * sizeof(double));
- for (int k = 0; k < sub_n; k++) {
- for (int l = 0; l < sub_n; l++) {
- sub_matrix[k][l] = A[k < i ? k : k + 1][l < j ? l : l + 1];
- }
- }
- double det_sub = determinant(sub_matrix, sub_n);
- int sign = (i + j) % 2 == 0 ? 1 : -1;
- adjoint[i][j] = sign * det_sub;
- free(sub_matrix);
- }
- }
- // Транспонирование матрицы алгебраических дополнений
- double** A_inv = malloc(n * sizeof(double*));
- for (int i = 0; i < n; i++) {
- A_inv[i] = malloc(n * sizeof(double));
- }
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- A_inv[i][j] = adjoint[j][i];
- }
- }
- for (int i = 0; i < n; i++) {
- free(adjoint[i]);
- }
- free(adjoint);
- return A_inv;
- }
- double determinant(Matrix A, int n) {
- double det = 0.0;
- if (n == 1) {
- det = A[0][0];
- } else if (n == 2) {
- det = A[0][0] * A[1][1] - A[0][1] * A[1][0];
- } else {
- for (int j = 0; j < n; j++) {
- double (*sub_matrix)[n - 1] = malloc((n - 1) * sizeof(double));
- for (int k = 1; k < n; k++) {
- for (int l = 0; l < n; l++) {
- sub_matrix[k - 1][l < j ? l : l + 1] = A[k][l];
- }
- }
- det += (A[0][j] * (j % 2 == 0 ? 1 : -1) * determinant(sub_matrix, n - 1));
- free(sub_matrix);
- }
- }
- return det;
- }
- int main() {
- int n;
- FILE *file = fopen("input.txt", "r");
- if (file == NULL) {
- printf("Error opening file.\n");
- return -1;
- }
- fscanf(file, "%d", &n);
- double (*A)[n] = malloc(n * sizeof(double));
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- fscanf(file, "%lf", &A[i][j]);
- }
- }
- fclose(file);
- double** A_inv = inverse_matrix(A, n);
- double norm_n = norm((Matrix) A_inv, n);
- printf("Норма невязки: %.2e\n", norm_n);
- for (int i = 0; i < n; i++) {
- free(A[i]);
- }
- free(A);
- for (int i = 0; i < n; i++) {
- free(A_inv[i]);
- }
- free(A_inv);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement