fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <iomanip>
  4. using namespace std;
  5.  
  6. double f(double x) {
  7. return x*x*x - x - 2;
  8. }
  9.  
  10. int main() {
  11. double x1, x2, x3, f1, f2, tolerance;
  12. int iteration = 0, max_iterations = 1000;
  13.  
  14. cout << "Enter the value of x1: ";
  15. cin >> x1;
  16. cout << "Enter the value of x2: ";
  17. cin >> x2;
  18. cout << "Enter tolerance value: ";
  19. cin >> tolerance;
  20.  
  21. cout << "\nIteration\t x1\t\t x2\t\t x3\t\t f(x1)\t\t f(x2)\n";
  22. cout << fixed << setprecision(6);
  23.  
  24. do {
  25. f1 = f(x1);
  26. f2 = f(x2);
  27.  
  28. if (fabs(f2 - f1) < 1e-12) {
  29. cout << "ভাগফল শূন্যের কাছাকাছি, গণনা করা যায় না।" << endl;
  30. break;
  31. }
  32.  
  33. x3 = (f2 * x1 - f1 * x2) / (f2 - f1);
  34. double fx3 = f(x3);
  35.  
  36. cout << iteration + 1 << "\t\t " << x1 << "\t " << x2 << "\t " << x3
  37. << "\t " << f1 << "\t " << f2 << endl;
  38.  
  39. x1 = x2;
  40. x2 = x3;
  41. f1 = f2;
  42. f2 = fx3;
  43.  
  44. iteration++;
  45.  
  46. if (iteration >= max_iterations) {
  47. cout << "সমাধান নির্ধারিত সংখ্যক ধাপে সন্নিকটে পৌঁছায়নি।" << endl;
  48. break;
  49. }
  50.  
  51. } while (fabs(f(x3)) > tolerance);
  52.  
  53. if (fabs(f(x3)) <= tolerance) {
  54. cout << "\nApproximate root = " << x3 << endl;
  55. }
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0s 5312KB
stdin
x0=1
x1=2
stdout
Enter the value of x1: Enter the value of x2: Enter tolerance value: 
Iteration	 x1		 x2		 x3		 f(x1)		 f(x2)
ভাগফল শূন্যের কাছাকাছি, গণনা করা যায় না।