fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cmath>
  4. using namespace std;
  5.  
  6. // ফাংশন f(x) = 2x² - x - 8
  7. double f(double x) {
  8. return 2 * x * x - x - 8;
  9. }
  10.  
  11. int main() {
  12. double x1, x2, x0, f1, f2, f0, error;
  13. int iteration = 1;
  14. const double EPSILON = 0.0001;
  15.  
  16. cout << "Enter the value of x1: ";
  17. cin >> x1;
  18. cout << "Enter the value of x2: ";
  19. cin >> x2;
  20.  
  21. f1 = f(x1);
  22. f2 = f(x2);
  23.  
  24. // প্রাথমিক অনুমানগুলোর মধ্যে ফাংশনের মানের চিহ্ন বিপরীত কিনা পরীক্ষা
  25. if (f1 * f2 > 0) {
  26. cout << "The initial guesses do not bracket any root." << endl;
  27. return 0;
  28. }
  29.  
  30. cout << "\nIteration x1 x2 x0 f(x1) f(x2) f(x0)\n";
  31.  
  32. do {
  33. // মধ্যবিন্দু নির্ণয়
  34. x0 = (x1 + x2) / 2.0;
  35. f0 = f(x0);
  36.  
  37. // ফলাফল প্রদর্শন
  38. cout << fixed << setprecision(6);
  39. cout << iteration << " "
  40. << x1 << " " << x2 << " "
  41. << x0 << " "
  42. << f1 << " "
  43. << f2 << " "
  44. << f0 << endl;
  45.  
  46. // নতুন সীমা নির্ধারণ
  47. if (f1 * f0 < 0) {
  48. x2 = x0;
  49. f2 = f0;
  50. } else {
  51. x1 = x0;
  52. f1 = f0;
  53. }
  54.  
  55. // ত্রুটি নির্ণয়
  56. error = fabs((x2 - x1) / x2);
  57. iteration++;
  58. } while (error > EPSILON);
  59.  
  60. cout << "\nApproximate root = " << x0 << endl;
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 0s 5324KB
stdin
-1
-2
0.0001
stdout
Enter the value of x1: Enter the value of x2: 
Iteration    x1            x2            x0            f(x1)        f(x2)        f(x0)
1            -1.000000     -2.000000     -1.500000     -5.000000     2.000000     -2.000000
2            -1.500000     -2.000000     -1.750000     -2.000000     2.000000     -0.125000
3            -1.750000     -2.000000     -1.875000     -0.125000     2.000000     0.906250
4            -1.750000     -1.875000     -1.812500     -0.125000     0.906250     0.382812
5            -1.750000     -1.812500     -1.781250     -0.125000     0.382812     0.126953
6            -1.750000     -1.781250     -1.765625     -0.125000     0.126953     0.000488
7            -1.750000     -1.765625     -1.757812     -0.125000     0.000488     -0.062378
8            -1.757812     -1.765625     -1.761719     -0.062378     0.000488     -0.030975
9            -1.761719     -1.765625     -1.763672     -0.030975     0.000488     -0.015251
10            -1.763672     -1.765625     -1.764648     -0.015251     0.000488     -0.007383
11            -1.764648     -1.765625     -1.765137     -0.007383     0.000488     -0.003448
12            -1.765137     -1.765625     -1.765381     -0.003448     0.000488     -0.001480
13            -1.765381     -1.765625     -1.765503     -0.001480     0.000488     -0.000496

Approximate root = -1.765503