fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6. double f(double x)
  7. {
  8. return x * x * x - 4;
  9. }
  10.  
  11. int main()
  12. {
  13. double x0, x1, x2, f0, f1, f2;
  14.  
  15. // Define maximum iterations and tolerance here
  16. int maxi = 10; // maximum number of iterations
  17. double t = 0.0001; // tolerance for stopping criterion
  18.  
  19. cout << "Enter the value of x0: ";
  20. cin >> x0;
  21. cout << "Enter the value of x1: ";
  22. cin >> x1;
  23.  
  24. f0 = f(x0);
  25. f1 = f(x1);
  26.  
  27. if (f0 * f1 > 0) {
  28. cout << "\nInvalid interval!.\n";
  29. return 0;
  30. }
  31.  
  32. cout << "\n-------------------------------------------------------------";
  33. cout << "\nIteration\t x0\t\t x1\t\t x2\t\t f0\t\t f1\t\t f2";
  34. cout << "\n-------------------------------------------------------------\n";
  35.  
  36. int i = 1;
  37. while (i <= maxi) {
  38. x2 = x0 - (f0 * (x1 - x0)) / (f1 - f0);
  39. f2 = f(x2);
  40.  
  41. cout << fixed << setprecision(6);
  42. cout << setw(3) << i << "\t"
  43. << x0 << "\t" << x1 << "\t" << x2 << "\t"
  44. << f0 << "\t" << f1 << "\t" << f2 << endl;
  45.  
  46. if (fabs(f2) < t) {
  47. break;
  48. }
  49.  
  50. if (f0 * f2 < 0) {
  51. x1 = x2;
  52. f1 = f2;
  53. } else {
  54. x0 = x2;
  55. f0 = f2;
  56. }
  57.  
  58. i++;
  59. }
  60.  
  61. cout << "\nApproximate root = " << x2 << endl;
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0.01s 5316KB
stdin
-3
2
stdout
Enter the value of x0: Enter the value of x1: 
-------------------------------------------------------------
Iteration	 x0		 x1		 x2		 f0		 f1		 f2
-------------------------------------------------------------
  1	-3.000000	2.000000	1.428571	-31.000000	4.000000	-1.084548
  2	1.428571	2.000000	1.550459	-1.084548	4.000000	-0.272818
  3	1.550459	2.000000	1.579162	-0.272818	4.000000	-0.061962
  4	1.579162	2.000000	1.585581	-0.061962	4.000000	-0.013740
  5	1.585581	2.000000	1.587000	-0.013740	4.000000	-0.003031
  6	1.587000	2.000000	1.587313	-0.003031	4.000000	-0.000668
  7	1.587313	2.000000	1.587382	-0.000668	4.000000	-0.000147
  8	1.587382	2.000000	1.587397	-0.000147	4.000000	-0.000032

Approximate root = 1.587397