24 std::vector<double> b) {
26 const std::size_t n = b.size();
28 throw std::invalid_argument(
"SolveLinearSystem: matrix/vector size mismatch");
30 for (
const std::vector<double>& row : A) {
31 if (row.size() != n) {
32 throw std::invalid_argument(
"SolveLinearSystem: matrix is not square");
37 for (std::size_t col = 0; col < n; ++col) {
39 std::size_t pivot = col;
40 double best = std::abs(A[col][col]);
41 for (std::size_t row = col + 1; row < n; ++row) {
42 const double candidate = std::abs(A[row][col]);
43 if (candidate > best) {
49 throw std::runtime_error(
"SolveLinearSystem: singular matrix");
52 std::swap(A[pivot], A[col]);
53 std::swap(b[pivot], b[col]);
57 for (std::size_t row = col + 1; row < n; ++row) {
58 const double factor = A[row][col] / A[col][col];
60 for (std::size_t c = col; c < n; ++c) {
61 A[row][c] -= factor * A[col][c];
63 b[row] -= factor * b[col];
69 std::vector<double> x(n, 0.0);
70 for (std::size_t i = n; i-- > 0;) {
72 for (std::size_t c = i + 1; c < n; ++c) {
73 sum -= A[i][c] * x[c];