-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGaussElimination.c
More file actions
129 lines (114 loc) · 2.92 KB
/
GaussElimination.c
File metadata and controls
129 lines (114 loc) · 2.92 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float absolute(float);
main()
{
int i,j,k,n,i_max;
float**A,*x,*b,temp,max;
FILE*f_in,*f_out,*f_t;
f_in=fopen("inputMatrix.txt","r");
fscanf(f_in,"%d",&n);
A=(float**)malloc(n*sizeof(float*));
for(i=0;i<n;i++)
{
A[i]=(float*)malloc(n*sizeof(float));
}
b=(float*)malloc(n*sizeof(float));
x=(float*)malloc(n*sizeof(float));
printf("Initializing Input\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
fscanf(f_in,"%f",&A[i][j]);
}
}
for(i=0;i<n;i++)
{
fscanf(f_in,"%f",&b[i]);
}
printf("Input Successfully Completed\n");
printf("Initializing Guassian Elemination\n");
clock_t start_t, end_t, total_t;
start_t = clock();
for(i=0;i<n;i++)
{
max=absolute(A[i][i]);
i_max=i;
for(j=i+1;j<n;j++)
{
if(absolute(A[j][i])>max)
{
max=absolute(A[j][i]);
i_max=j;
}
}
printf("\tPartial Pivoting for Row %d\n",i);
for(j=0;j<n;j++)
{
temp=A[i][j];
A[i][j]=A[i_max][j];
A[i_max][j]=temp;
}
temp=b[i];
b[i]=b[i_max];
b[i_max]=temp;
printf("\tClearing the lower triangle at Row %d\n",i);
for(j=0;j<i;j++)
{
for(k=j+1;k<n;k++)
{
A[i][k]-=A[i][j]*A[j][k];
}
b[i]-=A[i][j]*b[j];
A[i][j]=0;
}
printf("\tNormalizing with respect to diagonal element at Row %d\n",i);
for(j=i+1;j<n;j++)
{
A[i][j]/=A[i][i];
}
b[i]/=A[i][i];
A[i][i]=1;
}
/*for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%f\t",A[i][j]);
}
printf("\n");
}*/
printf("\tInitializing Backward Substitution\n");
for(i=n-1;i>=0;i--)
{
printf("\t\tComputing the element %d\n",i);
x[i]=b[i];
for(j=n-1;j>i;j--)
{
x[i]-=A[i][j]*x[j];
}
}
printf("\tBackward Substiitution Successfully Completed\n");
printf("Computation of the variables Successfully Completed\n");
end_t = clock();
total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC *1000;
f_t=fopen("Gauss_time.txt","a");
fprintf(f_t,"%d\t%f\n",n,(double)total_t);
printf("Total time taken for the Computation was %f ms\n", (double)total_t );
printf("Initializing Output of the Solution\n");
f_out=fopen("GaussEliminationSolution.txt","w");
for(i=0;i<n;i++)
{
fprintf(f_out,"%f\n",x[i]);
}
printf("Output of the Solution Successfully Completed\n");
}
float absolute(float x)
{
if(x<0)
return -x;
else
return x;
}