Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <math.h>
- #include <stdio.h>
- #define M 3
- static void print_matrix(const double a[][M]) {
- for (int i = 0; i < M; ++i) {
- for (int j = 0; j < M; ++j) { printf("%f\t", a[i][j]); }
- puts("");
- }
- }
- static double determinant(const double a[][M]) {
- double D = 0.;
- for (int i = 0; i < M; i++) {
- D += a[0][i] * (a[1][(i + 1) % 3] * a[2][(i + 2) % 3] -
- a[1][(i + 2) % 3] * a[2][(i + 1) % 3]);
- }
- return D;
- }
- static void cofactor(const double a[][M], double b[][M]) {
- for (int i = 0; i < M; i++) {
- for (int j = 0; j < M; j++) {
- b[i][j] = a[(i + 1) % 3][(j + 1) % 3] * a[(i + 2) % 3][(j + 2) % 3] -
- a[(i + 1) % 3][(j + 2) % 3] * a[(i + 2) % 3][(j + 1) % 3];
- }
- }
- }
- static void inverse(const double a[][M], double b[][M]) {
- double det = determinant(a);
- cofactor(a, b);
- for (int i = 0; i < M; ++i) {
- for (int j = 0; j < M; ++j) {
- if (j < i) {
- continue;
- } else if (i == j) {
- b[i][i] /= det;
- continue;
- }
- double t = b[i][j];
- b[i][j] = b[j][i] / det, b[j][i] = t / det;
- }
- }
- }
- static void multi(const double a[][M], const double b[][M], double c[][M]) {
- for (int i = 0; i < M; ++i) {
- for (int j = 0; j < M; ++j) {
- double s = 0.;
- for (int k = 0; k < M; ++k) { s += a[i][k] * b[k][j]; }
- c[i][j] = s;
- }
- }
- }
- int main(void) {
- double a[M][M] = {{4.0, 1.0, -5.0}, {3.0, -2.0, 1.0}, {5.0, 3.0, -5.0}};
- printf("A =\n"), print_matrix(a);
- printf("det(A) = %f\n", determinant(a));
- double b[M][M] = {0};
- cofactor(a, b), printf("cofactor(A) =\n"), print_matrix(b);
- inverse(a, b), printf("inverse(A) =\n"), print_matrix(b);
- double c[M][M] = {0};
- multi(a, b, c), printf("check. A * inverse(A) =\n"), print_matrix(c);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement