A lightweight C++ Newton-Raphson solver for nonlinear systems of equations.
Instead of explicitly computing the Jacobian inverse,
the solver directly solves
using Gaussian elimination, which is typically faster and numerically more stable.
Solve the nonlinear system:
#include "../include/newton.hpp"
#include <iostream>
int main() {
using pivot_nr::Vec;
using pivot_nr::Mat;
pivot_nr::SystemFn systemFn = [](const Vec& x, Vec& f) {
f[0] = x[0]*x[0] + x[1]*x[1] - 4.0;
f[1] = x[0]*x[1] - 1.0;
};
pivot_nr::JacobianFn jacobianFn = [](const Vec& x, Mat& J) {
J[0][0] = 2.0*x[0]; J[0][1] = 2.0*x[1];
J[1][0] = x[1]; J[1][1] = x[0];
};
pivot_nr::RootFinderResult res = pivot_nr::newton_solve(systemFn, jacobianFn, Vec{2.0, 1.0});
std::cout << "2D nonlinear system\n";
std::cout << " (x1, x2) = (" << res.x[0] << ", " << res.x[1] << ")\n";
std::cout << " Residual = " << res.residual << "\n";
std::cout << " Iterations = " << res.iterations << "\n";
return 0;
} make clean
make
cd bin
./newton- make Default: debug build
- make debug Same as above
- make release Optimised build
- make profile Optimised + debug symbols (for perf)
- make clean Clean all artefacts