#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
// Define the function f(x) = x^3 - x - 3
double f(double x) {
return pow(x, 3) - x - 3;
}
// Define the derivative f'(x) = 3x^2 - 1
double f_prime(double x) {
return 3 * pow(x, 2) - 1;
}
int main() {
double x0 = 3.0; // Initial guess
double x1;
double tolerance = 1e-6;
int max_iterations = 100;
int iteration = 1;
cout << fixed << setprecision(6);
cout << "**************************************" << endl;
cout << "ITERATION\tX\t\tf(X)\t\tf'(X)" << endl;
cout << "**************************************" << endl;
while (iteration <= max_iterations) {
double fx = f(x0);
double fpx = f_prime(x0);
if (fpx == 0.0) {
cout << "Derivative is zero. No solution found." << endl;
return -1;
}
x1 = x0 - fx / fpx;
cout << iteration << "\t\t" << x0 << "\t" << fx << "\t" << fpx << endl;
if (fabs((x1 - x0) / x1) < tolerance) {
cout << "**************************************" << endl;
cout << "THE ROOT OF EQUATION IS " << x1 << endl;
break;
}
x0 = x1;
iteration++;
}
if (iteration > max_iterations) {
cout << "Did not converge to a solution within the maximum number of iterations." << endl;
}
return 0;
}