#include <bits/stdc++.h>
using namespace std;
// Modified function name
double customFunc(double val) {
return (2.0 * val * val * val + 3.0 * val - 1.0);
}
int main() {
double left, right, midpoint, f_left, f_right, f_mid, tolerance = 0.0001, root;
int iteration = 0;
// Input loop instead of goto
while (true) {
cout << "Enter two initial guesses: ";
cin >> left >> right;
f_left = customFunc(left);
f_right = customFunc(right);
if (f_left * f_right < 0) {
break;
} else {
cout << "Invalid interval. Try again.\n";
}
}
// First midpoint calculation
midpoint = (left + right) / 2.0;
f_mid = customFunc(midpoint);
if (f_mid == 0) {
cout << fixed << setprecision(8);
cout << "Exact root found: " << midpoint << endl;
return 0;
}
// Header for output
cout << "Iter\tMidpoint\tLeft\tRight\tf(Mid)\tf(Left)\tf(Right)\n";
cout << iteration << "\t" << fixed << setprecision(8) << midpoint << "\t"
<< left << "\t" << right << "\t"
<< f_mid << "\t" << f_left << "\t" << f_right << endl;
while (true) {
midpoint = (left + right) / 2.0;
f_mid = customFunc(midpoint);
iteration++;
cout << iteration << "\t" << fixed << setprecision(8) << midpoint << "\t"
<< left << "\t" << right << "\t"
<< f_mid << "\t" << f_left << "\t" << f_right << endl;
if (fabs((right - left) / right) < tolerance || iteration > 8) {
break;
}
if (f_left * f_mid < 0) {
right = midpoint;
f_right = f_mid;
} else {
left = midpoint;
f_left = f_mid;
}
root = midpoint;
}
cout << fixed << setprecision(8) << "Approximate root = " << root << endl;
return 0;
}