-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathl_ex_2.1.c
80 lines (71 loc) · 1.97 KB
/
l_ex_2.1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#define N 3
void CreateIdentityMat(double *I) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i == j) {
I[i*N+j] = 1.0;
} else {
I[i*N+j] = 0.0;
}
}
}
}
double CalculateDeterminant(double *A) {
double det = 0.0;
det += A[0] * (A[4]*A[8] - A[5]*A[7]);
det -= A[1] * (A[3]*A[8] - A[5]*A[6]);
det += A[2] * (A[3]*A[7] - A[4]*A[6]);
return det;
}
void CreateDxyz_mat(double *A, double *I, int A_colNum, double *Dxyz, int invA_colNum) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (j == A_colNum) {
Dxyz[i*N+j] = I[i*N+invA_colNum];
} else {
Dxyz[i*N+j] = A[i*N+j];
}
}
}
}
void CramersRuleForInverse(double *A) {
double detA = CalculateDeterminant(A);
if (detA == 0.0) {
printf("The matrix is singular, inverse does not exist.\n");
return;
}
double Ainv[N*N];
double I[N*N];
CreateIdentityMat(I);
for (int i = 0; i < N; i++) {
double Dx[N*N], Dy[N*N], Dz[N*N];
CreateDxyz_mat(A, I, i, Dx, 0);
CreateDxyz_mat(A, I, i, Dy, 1);
CreateDxyz_mat(A, I, i, Dz, 2);
double detDx = CalculateDeterminant(Dx);
double detDy = CalculateDeterminant(Dy);
double detDz = CalculateDeterminant(Dz);
Ainv[i*N+0] = detDx / detA;
Ainv[i*N+1] = detDy / detA;
Ainv[i*N+2] = detDz / detA;
}
printf("The inverse of the matrix is:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%f ", Ainv[i*N+j]);
}
printf("\n");
}
}
int main() {
double A[N*N];
printf("Enter the elements of the matrix A:\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
scanf("%lf", &A[i*N+j]);
}
}
CramersRuleForInverse(A);
return 0;
}