Chi-Tech
serial_newton_iteration.cc
Go to the documentation of this file.
2
3#include "chi_runtime.h"
4#include "chi_log.h"
5
6#include <iomanip>
7
8/**Newton iteration.*/
10 NewtonIteration(const NonLinearFunction &non_linear_function,
11 const VecDbl &x_0,
12 const unsigned int max_iters,
13 const double epsilon,
14 const bool verbose/*=false*/)
15{
16 //=================================== Verbose printing lambda
17 auto PrintIterationInfo = [](unsigned int i, const VecDbl& x_i,
18 const VecDbl& F_x_i,
19 double L2_norm_F_x_i)
20 {
21 std::stringstream output;
22 output << "Iteration " << std::setw(3) << i << ": x_i=";
23 for (auto value : x_i)
24 output << std::showpos << std::scientific << std::setprecision(3)
25 << value << " ";
26 output << "F_x_i=";
27 for (auto value : F_x_i)
28 output << std::showpos << std::scientific << std::setprecision(3)
29 << value << " ";
30 output << "L2_norm_F_x_i=" << L2_norm_F_x_i;
31
32 Chi::log.Log() << output.str();
33 };
34
35 //=================================== Declare and init variables
36 VecDbl x_i = x_0;
37 VecDbl F_x_i = non_linear_function.F(x_i);
38 MatDbl J_x_i_inv = chi_math::Inverse(non_linear_function.J(x_i));
39
40 double L2_norm_F_x_i = chi_math::Vec2Norm(F_x_i);
41
42 if (verbose) PrintIterationInfo(0, x_i, F_x_i, L2_norm_F_x_i);
43
44 //=================================== Perform iterations
45 unsigned int i = 0;
46 while (L2_norm_F_x_i >= epsilon and i < max_iters)
47 {
48 ++i;
49 x_i = x_i - MatMul(J_x_i_inv, F_x_i);
50
51 F_x_i = non_linear_function.F(x_i);
52 J_x_i_inv = chi_math::Inverse(non_linear_function.J(x_i));
53
54 L2_norm_F_x_i = chi_math::Vec2Norm(F_x_i);
55
56 if (verbose) PrintIterationInfo(i, x_i, F_x_i, L2_norm_F_x_i);
57 }
58
59 return x_i;
60}
std::vector< VecDbl > MatDbl
Definition: chi_math.h:13
std::vector< double > VecDbl
Definition: chi_math.h:12
static chi::ChiLog & log
Definition: chi_runtime.h:81
LogStream Log(LOG_LVL level=LOG_0)
Definition: chi_log.cc:35
virtual MatDbl J(const VecDbl &x) const
virtual VecDbl F(const VecDbl &x) const
MatDbl Inverse(const MatDbl &A)
VecDbl NewtonIteration(const NonLinearFunction &non_linear_function, const VecDbl &x_0, unsigned int max_iters, double epsilon, bool verbose=false)
MatDbl MatMul(const MatDbl &A, const double c)
double Vec2Norm(const VecDbl &x)