#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
double function(double x) {
return x * x - 34.0;
}
void secant_method(double x1, double x2, double tolerance) {
double f1 = function(x1);
double f2 = function(x2);
double x3;
int iteration = 0;
cout << setprecision(6) << fixed;
cout << "--- Secant Method for f(x) = x^2 - 34 ---" << endl;
cout << "Initial Guesses (x1, x2): (" << x1 << ", " << x2 << ")" << endl;
cout << "Tolerance (E): " << scientific << tolerance << fixed << endl;
cout << "\n";
cout << setw(10) << "Iter"
<< setw(15) << "x1"
<< setw(15) << "x2"
<< setw(15) << "x3"
<< setw(15) << "f(x1)"
<< setw(15) << "f(x2)"
<< setw(15) << "f(x3)" << endl;
cout << string(95, '-') << endl;
while (abs(function(x2)) >= tolerance && iteration < 50) {
iteration++;
if (abs(f2 - f1) < 1e-8) {
cout << "Error: Denominator near zero. Secant line is almost horizontal." << endl;
break;
}
x3 = x2 - (f2 * (x2 - x1)) / (f2 - f1);
double f3 = function(x3);
cout << setw(10) << iteration
<< setw(15) << x1
<< setw(15) << x2
<< setw(15) << x3
<< setw(15) << f1
<< setw(15) << f2
<< setw(15) << f3 << endl;
x1 = x2;
f1 = f2;
x2 = x3;
f2 = f3;
if (abs(f3) < tolerance) {
break;
}
}
cout << string(95, '-') << endl;
cout << "The final root is approximately: " << x2 << endl;
cout << "Found after " << iteration << " iterations." << endl;
}
int main() {
double x1_initial = 4.0;
double x2_initial = 2.0;
double tolerance = 0.000001;
secant_method(x1_initial, x2_initial, tolerance);
return 0;
}