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