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