fork download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. // Define the function whose root we want to find
  6. double f(double x) {
  7. return x * x * x + x * x - 1; // Example: f(x) = x^3 + x^2 - 1
  8. }
  9.  
  10. int main() {
  11. double x1, x2, x0, f1, f2, f0, E;
  12. int maxIter, iteration = 1;
  13.  
  14. // Input initial guesses and tolerance
  15. cout << "Enter the value of x1: ";
  16. cin >> x1;
  17. cout << "Enter the value of x2: ";
  18. cin >> x2;
  19. cout << "Enter desired tolerance (E): ";
  20. cin >> E;
  21. cout << "Enter maximum number of iterations: ";
  22. cin >> maxIter;
  23.  
  24. f1 = f(x1);
  25. f2 = f(x2);
  26.  
  27. // Check if initial guesses bracket a root
  28. if (f1 * f2 > 0) {
  29. cout << "Incorrect initial guesses. They do not bracket a root.\n";
  30. return 1;
  31. }
  32.  
  33. cout << "Iteration\tx1\t\tx2\t\tx0\t\tf(x0)\n";
  34. cout << "--------------------------------------------------------------\n";
  35.  
  36. do {
  37. x0 = (x1 + x2) / 2;
  38. f0 = f(x0);
  39.  
  40. cout << iteration << "\t\t" << x1 << "\t" << x2 << "\t" << x0 << "\t" << f0 << endl;
  41.  
  42. if (f1 * f0 < 0) {
  43. x2 = x0;
  44. f2 = f0;
  45. } else {
  46. x1 = x0;
  47. f1 = f0;
  48. }
  49.  
  50. iteration++;
  51.  
  52. if (fabs((x2 - x1) / x2) < E) break;
  53.  
  54. } while (iteration <= maxIter);
  55.  
  56. cout << "\nApproximate root = " << (x1 + x2) / 2 << endl;
  57.  
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0.01s 5292KB
stdin
-1
3
stdout
Enter the value of x1: Enter the value of x2: Enter desired tolerance (E): Enter maximum number of iterations: Iteration	x1		x2		x0		f(x0)
--------------------------------------------------------------
1		-1	3	1	1

Approximate root = 0