Gaussian elimination
unknown
c_cpp
4 years ago
1.5 kB
5
Indexable
const int MAXN = ;
// Initialize
struct Gauss
{
double eps = 1e-6;
int gauss(int n, int m, double a[MAXN][MAXN], double ans[MAXN]) {
int pos[MAXN];
memset(pos, 0, sizeof(pos));
bool parameters = false;
int row = 1, col = 1;
for (; row <= n && col <= m; col++) {
int pivot = row;
for (int i = row; i <= n; i++)
if (abs(a[i][col]) > abs(a[pivot][col]))
pivot = i;
if (abs(a[pivot][col]) < eps) {
parameters = true;
continue;
}
for (int i = 1; i <= m + 1; i++)
swap(a[row][i], a[pivot][i]);
pos[col] = row;
double div = a[row][col];
for (int i = 1; i <= m + 1; i++)
a[row][i] /= div;
for (int i = 1; i <= n; i++) {
if (i == row)
continue;
div = a[i][col];
for (int j = 1; j <= m + 1; j++)
a[i][j] -= a[row][j] * div;
}
row++;
}
for (int i = 1; i <= m; i++)
if (pos[i] != 0)
ans[i] = a[pos[i]][m + 1];
else
ans[i] = 0;
for (int i = 1; i <= n; i++) {
double sum = 0;
for (int j = 1; j <= m; j++)
sum += ans[j] * a[i][j];
if (abs(sum - a[i][m + 1]) > eps)
return 0;
}
if (parameters)
return INT_MAX;
return 1;
}
};
Editor is loading...