Gaussian elimination: Difference between revisions

Content added Content deleted
(Added C++ solution)
m (C++ - avoid division by zero)
Line 834: Line 834:
=={{header|C++}}==
=={{header|C++}}==
{{trans|Go}}
{{trans|Go}}
<lang cpp>#include <cassert>
<lang cpp>#include <algorithm>
#include <cassert>
#include <cmath>
#include <cmath>
#include <iomanip>
#include <iomanip>
Line 904: Line 905:
for (size_t i = k; i < n; ++i) {
for (size_t i = k; i < n; ++i) {
// compute scale factor = max abs in row
// compute scale factor = max abs in row
scalar_type scale_factor = -1;
scalar_type scale_factor = 0;
for (size_t j = k; j < n; ++j) {
for (size_t j = k; j < n; ++j)
scalar_type value = std::abs(a(i, j));
scale_factor = std::max(std::abs(a(i, j)), scale_factor);
if (value > scale_factor)
if (scale_factor == 0)
scale_factor = value;
continue;
}
// scale the abs used to pick the pivot
// scale the abs used to pick the pivot
scalar_type abs = std::abs(a(i, k))/scale_factor;
scalar_type abs = std::abs(a(i, k))/scale_factor;