Skip to content

Commit c143fd0

Browse files
author
Jason Boutte
committed
Adds new gaussian elimination algorithm
1 parent 9930682 commit c143fd0

File tree

1 file changed

+73
-4
lines changed

1 file changed

+73
-4
lines changed

lab3/gauss.c

Lines changed: 73 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
#include <math.h>
22
#include <stdio.h>
33
#include <stdlib.h>
4+
#include <string.h>
45

56
#define MAX_RAND 1.0e2 //1.0e6
67

7-
void gen_augmented_matrix(double **matrix, int n);
8+
void swap_pivot(double **matrix, int col, int n);
9+
void generate_aug_matrix(double **matrix, int n);
10+
void print_aug_matrix(double **matrix, int n);
811
void print_usage(char *prog);
912

1013
int main(int argc, char **argv) {
@@ -14,21 +17,47 @@ int main(int argc, char **argv) {
1417
exit(1);
1518
}
1619

17-
int n, i, j, k;
20+
int n;
21+
int i, j, k;
22+
double factor;
23+
double interm;
24+
double *result;
1825
double **matrix;
1926

2027
srand(time(NULL));
2128
srand48(time(NULL));
2229

2330
n = atoi(argv[1]);
2431

32+
result = malloc(n * sizeof(double));
33+
34+
memset(result, 0, n * sizeof(double));
35+
2536
matrix = malloc(n * sizeof(double));
2637

2738
for (i = 0; i < n; ++i) {
2839
matrix[i] = malloc((n + 1) * sizeof(double));
2940
}
3041

31-
gen_augmented_matrix(matrix, n);
42+
generate_aug_matrix(matrix, n);
43+
44+
for (i = 0; i < n; ++i) {
45+
swap_pivot(matrix, i, n);
46+
47+
print_aug_matrix(matrix, n);
48+
49+
for (j = i + 1; j < n; ++j) {
50+
factor = matrix[j][i] / matrix[i][i];
51+
52+
printf("Factor %f\n", factor);
53+
54+
for (k = 0; k < n + 1; ++k) {
55+
interm = factor * matrix[i][k];
56+
57+
matrix[j][k] -= interm;
58+
}
59+
}
60+
}
3261

3362
for (i = 0; i < n; ++i) {
3463
free(matrix[i]);
@@ -39,7 +68,31 @@ int main(int argc, char **argv) {
3968
return 0;
4069
}
4170

42-
void gen_augmented_matrix(double **matrix, int n) {
71+
void swap_pivot(double **matrix, int col, int n) {
72+
int i;
73+
int pivot;
74+
double max;
75+
double value;
76+
double *temp;
77+
78+
for (i = col; i < n; ++i) {
79+
value = fabs(matrix[i][col]);
80+
81+
if (value > max) {
82+
pivot = i;
83+
84+
max = value;
85+
}
86+
}
87+
88+
temp = matrix[pivot];
89+
90+
matrix[pivot] = matrix[col];
91+
92+
matrix[col] = temp;
93+
}
94+
95+
void generate_aug_matrix(double **matrix, int n) {
4396
int i, j;
4497

4598
for (i = 0; i < n; ++i) {
@@ -53,6 +106,22 @@ void gen_augmented_matrix(double **matrix, int n) {
53106
}
54107
}
55108

109+
void print_aug_matrix(double **matrix, int n) {
110+
int i, j;
111+
112+
printf("\n");
113+
114+
for (i = 0; i < n; ++i) {
115+
for (j = 0; j < n; ++j) {
116+
printf("%.2f\t", matrix[i][j]);
117+
}
118+
119+
printf("\tx%i\t%.2f\n", i+1, matrix[i][n]);
120+
}
121+
122+
printf("\n");
123+
}
124+
56125
void print_usage(char *prog) {
57126
printf("%s n threads\n", prog);
58127
printf("n - Size of the matrix\n");

0 commit comments

Comments
 (0)