Pagini recente » Cod sursa (job #222942) | Cod sursa (job #1318792) | Cod sursa (job #2440525) | Cod sursa (job #2818548) | Cod sursa (job #2497050)
#include <iostream>
#include <fstream>
#include <iomanip>
std::ifstream f("gauss.in");
std::ofstream t("gauss.out");
#define NMAX 310
#define EPSILON 1e-8
template <typename T>
using Matrix = T[NMAX][NMAX];
template <typename T>
using Vector = T[NMAX];
int main() {
Matrix<float> A;
Vector<float> b;
Vector<float> x = {};
int n, m;
f >> n >> m;
auto abs = [](float target) {
return target < 0 ? -target : target;
};
auto subtract_line_with_scalar = [&A, &b, m](int dst, int src, float scalar, int start = 0) mutable {
for (int i = start; i < m; ++i)
A[dst][i] -= A[src][i] * scalar;
b[dst] -= b[src] * scalar;
};
auto divide_line_with_scalar = [&A, &b, m](int dst, float scalar, int start = 0) mutable {
for (int i = start; i < m; ++i)
A[dst][i] /= scalar;
b[dst] /= scalar;
};
// reading the matrix and results
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j)
f >> A[i][j];
f >> b[i];
}
for (int i = 0; i < m; ++i) { // for each column
divide_line_with_scalar(i, A[i][i], i); // no pivoting, but scaling
for (int j = i + 1; j < n; ++j) { // rest to 0
subtract_line_with_scalar(j, i, A[j][i], i);
}
}
float sigma;
// now perform back substitution
for (int i = n - 1, aux = n < m ? n - 1 : m - 1; i >= 0; --i) {
sigma = .0;
for (int j = n < m ? n - 1 : m - 1; j > aux; --j) {
sigma += x[j] * A[i][j];
}
if (abs(sigma + A[i][aux]) < abs(EPSILON) && abs(b[i]) > abs(EPSILON)) {
t << "Imposibil\n";
return 0;
}
else if (A[i][aux] > abs(EPSILON)) {
x[aux] = (b[i] - sigma) / A[i][aux];
--aux;
}
}
t << std::setprecision(10) << std::fixed;
for (int i = 0; i < m; ++i)
t << x[i] << " ";
return 0;
}