#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
double function(double x) {
return x * x * x - x - 3.0;
}
double derivative(double x) {
return 3.0 * x * x - 1.0;
}
void newton_raphson_method(double x0, double tolerance) {
double xi = x0;
double xi_plus_1;
double error;
int iteration = 0;
cout << setprecision(6) << fixed;
cout << "--- Newton-Raphson Method for f(x) = x^3 - x - 3 ---" << endl;
cout << "Initial Guess (x0): " << x0 << endl;
cout << "Tolerance (E): " << scientific << tolerance << fixed << endl;
cout << "\n";
cout << setw(10) << "Iter"
<< setw(15) << "xi"
<< setw(15) << "f(xi)"
<< setw(15) << "f'(xi)"
<< setw(15) << "xi+1"
<< setw(15) << "Rel. Error" << endl;
cout << string(85, '-') << endl;
do {
iteration++;
double f_xi = function(xi);
double f_prime_xi = derivative(xi);
if (abs(f_prime_xi) < 1e-8) {
cout << "Error: Derivative is near zero at xi = " << xi << endl;
break;
}
xi_plus_1 = xi - (f_xi / f_prime_xi);
error = abs((xi_plus_1 - xi) / xi_plus_1);
cout << setw(10) << iteration
<< setw(15) << xi
<< setw(15) << f_xi
<< setw(15) << f_prime_xi
<< setw(15) << xi_plus_1
<< setw(15) << error << endl;
xi = xi_plus_1;
} while (error >= tolerance && iteration < 50);
cout << string(85, '-') << endl;
cout << "The final root is approximately: " << xi << endl;
cout << "Found after " << iteration << " iterations." << endl;
}
int main() {
double initial_guess = 3.0;
double tolerance = 0.000001;
newton_raphson_method(initial_guess, tolerance);
return 0;
}