-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFinal_Code.cpp
132 lines (115 loc) · 2.64 KB
/
Final_Code.cpp
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
130
131
132
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i, j, k, n;
float count = 0;
cout << "Enter number of variables: ";
cin >> n;
float main[2*n][2*n]; // This is the array of order 2nx2n in which the original matrix will be stored
float t;
float inv[2*n][2*n]; // this is the array in which the inverse of the matrix will be stored
float consta[n][1]; // this is the array in which of the values of the constants will be stored
float ans[n][1]; // this is the array in which our final answers will be stored
// Storing the coefficients and the constants of the equation
for (i = 0; i < n; i++)
{
for (j = 0; j <= n; j++)
{
if (j == n)
{
cout << "Enter the value of the constant for equation number " << i + 1 << ": ";
cin >> consta[i][0];
}
else
{
cout << "Enter coefficient of equation number " << i + 1 << " x" << j + 1 << ": ";
cin >> main[i][j];
}
}
}
// Initialising the second half of the matrix as an identity matrix
for (i = 0; i < n; i++)
{
for (j = n; j < 2 * n; j++)
{
if (i == j - n)
{
main[i][j] = 1;
}
else
{
main[i][j] = 0;
}
}
}
// Calculating the inverse of the matrix now
for (i = 0; i < n; i++)
{
t = main[i][i];
for (j = i; j < 2 * n; j++)
{
main[i][j] = main[i][j] / t;
}
for (j = 0; j < n; j++)
{
if(i!=j){
t=main[j][i];
for (k = 0; k < 2*n; k++)
{
main[j][k]=main[j][k]-(t*main[i][k]);
}
}
}
}
// Checking to see if there any invalid values in the inverse matrix and then storing the values in an NxN matrix for further operations
for (i = 0; i < n; i++)
{
int z=0;
for (j = n; j < 2*n; j++)
{
if(isinf(main[i][j]==1||isnan(main[i][j]==1))){
count=1;
break;
}
inv[i][z++]=main[i][j];
}
}
//If there are no invalid values in the inverse matrix, then we multiply the inverse matrix with the matrix containing the constants
if(count ==0){
//Displaying the inverse matrix
// cout<<"\n\nInverse Matrix\n\n";
// for(i = 0;i<n;i++){
// for (j =0;j < n;j++)
// {
// cout<<"\t"<<inv[i][j];
// }
// cout<<"\n";
// }
//Initialising all the values of the answer matrix to 0
for ( i = 0; i < n; i++)
{
ans[i][0]=0;
}
//Multiplying the inverse matrix to the constants matrix
for (i = 0; i < n; i++)
{
for (j = 0; j < 1; j++)
{
for(k = 0;k<n;++k){
ans[i][j]+= inv[i][k]*consta[k][j];
}
}
}
//Displaying the values of the variables
for(i=0;i<n;i++){
for(j=0;j<1;j++)
cout<<"x"<<i+1<<": "<<ans[i][0];
cout<<"\n";
}
}
else{
cout<<"\nThe system of equations has no unique solution";
}
return 0;
}