template<typename Real>
class Utils::AlgoHNewton< Real >
Class for solving \( f(x)=0 \) without the usew of derivative.
Usage simple example:
To use this class, first wrap your function in a derived class. For instance, for the function \( f(x) = x^2 - 2 \), you can define:
public:
double eval(
double x)
const override {
return x*x - 2; }
double D (
double x)
const override {
return 2*x; }
};
Abstract base class for defining mathematical functions used in the zero search algorithm.
Definition Utils_AlgoHNewton.hh:81
virtual Real eval(Real x) const =0
virtual Real D(Real x) const =0
Next, instantiate the function and the solver. Then, call the desired method to find the root:
HNewton<real_type> solver;
Fun1 f;
real_type x_solution = solver.eval2(
a,
b,f);
Real b() const
Definition Utils_AlgoHNewton.hh:313
Real a() const
Definition Utils_AlgoHNewton.hh:312
If the method converges, x_solution
will contain the computed solution.
Usage Detailed Example:
To create a custom function, derive from this class and implement the required methods. Here is an example for the function \( f(x) = x^2 - 2 \):
Step 1: including headers
To use the HNewton
class, include the necessary headers:
#include "Utils_HNewton.hh"
defining your function
Define the function for which you want to find the root. The function must take a single argument (the variable for which you're solving) and return a value.
For example, to find the root of \( \sin(x) - \frac{x}{2} = 0 \):
public:
double eval(double x) const override { return sin(x) - x / 2; }
double D (double x) const override { return cos(x) - 0.5; }
};
static Fun1 myFunction;
Calling the solver
To find a root, call the eval
method with the initial guesses for the root (interval [a, b]
). Here's an example of how to set up a program to find a root:
int
main() {
HNewton<real_type> solver;
real_type root = solver.eval(
a,
b, myFunction);
cout << "Root found: " << root << endl;
cout << "f(root) = " << myFunction.eval(root) << endl;
return 0;
}
Analyzing results
After calling the eval
method, you can check the number of iterations, number of function evaluations, and whether the algorithm converged:
cout << "Iterations: " << solver.used_iter() << endl;
cout << "Function Evaluations: " << solver.num_fun_eval() << endl;
cout << "Function Derivative Evaluations: " << solver.num_fun_D_eval() << endl;
cout << "Converged: " << (solver.converged() ? "Yes" : "No") << endl;