fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. double f(double x)
  5. {
  6. return x * x * x - 4;
  7. }
  8.  
  9. int main()
  10. {
  11. double x0, x1, x2, f0, f1, f2;
  12.  
  13. int maxi = 10;
  14. double t = 0.0001;
  15.  
  16. cout << "Enter the value of x0: ";
  17. cin >> x0;
  18. cout << "Enter the value of x1: ";
  19. cin >> x1;
  20.  
  21. f0 = f(x0);
  22. f1 = f(x1);
  23.  
  24. if (f0 * f1 > 0) {
  25. cout << "\nInvalid interval!.\n";
  26. return 0;
  27. }
  28.  
  29. cout << "\n-------------------------------------------------------------";
  30. cout << "\nIteration\t x0\t\t x1\t\t x2\t\t f0\t\t f1\t\t f2";
  31. cout << "\n-------------------------------------------------------------\n";
  32.  
  33. int i = 1;
  34. while (i <= maxi)
  35. {
  36. x2 = x0 - (f0 * (x1 - x0)) / (f1 - f0);
  37. f2 = f(x2);
  38.  
  39. cout << fixed << setprecision(6);
  40. cout << setw(3) << i << "\t"
  41. << x0 << "\t" << x1 << "\t" << x2 << "\t"
  42. << f0 << "\t" << f1 << "\t" << f2 << endl;
  43.  
  44. if (fabs(f2) < t) {
  45. break;
  46. }
  47. if (f0 * f2 < 0)
  48. {
  49. x1 = x2;
  50. f1 = f2;
  51. } else {
  52. x0 = x2;
  53. f0 = f2;
  54. }
  55.  
  56. i++;
  57. }
  58.  
  59. cout << "\nApproximate root = " << x2 << endl;
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0s 5312KB
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