It employs the technique of linear approximation and involves using the tangent line to approximate the roots.
The method is highly efficient and converges rapidly, providing robust solutions in fewer iterations.
File content:
{{{{{
#include <iostream>
#include <cmath>
using namespace std;
const double EPS = 0.000001;
double function(double x0)
{
// x0^2 - 3*x0 + 2 = (x0 - 1)(x0 - 2)
return x0*x0 - 3*x0 + 2;
}
double derivative_of_the_function(double x0)
{
return 2*x0 - 3;
}
int main()
{
int max;
int i = 0;
double x1, x0;
cout << "Newton-Raphson Method in C++" << endl;
cout << "Maximum number of iterations: ";
max = 100;
cout << max << endl;
cout << "The first approximation: ";
x0 = 0; // you get the root 1
//x0 = 3; // you get the root 2
cout << x0 << endl;
bool flagStopLoop = false;
do
{
x1 = x0 - (function(x0) / derivative_of_the_function(x0));
i++;
if( fabs(x1 - x0) <= EPS )
{
flagStopLoop = true;
}
else if( i > max )
{
flagStopLoop = true;
}
else
{
x0 = x1;
}
} while( !flagStopLoop );
cout << "The root of the function after " << i << " iteration is "
<< x1 << endl;
return 0;
}