fork download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. double f(double x) {
  6. return 2 * x * x * x + 3 * x - 1;
  7. }
  8.  
  9. int main() {
  10. double x1 = 0, x2 = 1, x0, f1, f2, f0;
  11. double E = 1e-8;
  12. int i = 0;
  13.  
  14. f1 = f(x1);
  15. f2 = f(x2);
  16.  
  17. if (f1 * f2 > 0) {
  18. cout << "No root in this interval.\n";
  19. return 0;
  20. }
  21.  
  22. cout << "Iter\t x1\t\t x2\t\t x0\t\t f(x0)\n";
  23.  
  24. while (fabs((x2 - x1) / x2) > E) {
  25. i++;
  26. x0 = (x1 + x2) / 2;
  27. f0 = f(x0);
  28.  
  29. cout << i << "\t" << x1 << "\t" << x2 << "\t" << x0 << "\t" << f0 << endl;
  30.  
  31. if (f1 * f0 < 0)
  32. x2 = x0;
  33. else {
  34. x1 = x0;
  35. f1 = f0;
  36. }
  37. }
  38.  
  39. cout << "\nApproximate root = " << (x1 + x2) / 2 << endl;
  40. cout << "Total iterations = " << i << endl;
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 5316KB
stdin
4 
-2
stdout
Iter	 x1		 x2		 x0		 f(x0)
1	0	1	0.5	0.75
2	0	0.5	0.25	-0.21875
3	0.25	0.5	0.375	0.230469
4	0.25	0.375	0.3125	-0.00146484
5	0.3125	0.375	0.34375	0.112488
6	0.3125	0.34375	0.328125	0.0550308
7	0.3125	0.328125	0.320312	0.0266657
8	0.3125	0.320312	0.316406	0.0125715
9	0.3125	0.316406	0.314453	0.00554611
10	0.3125	0.314453	0.313477	0.00203884
11	0.3125	0.313477	0.312988	0.00028655
12	0.3125	0.312988	0.312744	-0.000589259
13	0.312744	0.312988	0.312866	-0.000151383
14	0.312866	0.312988	0.312927	6.75765e-05
15	0.312866	0.312927	0.312897	-4.19049e-05
16	0.312897	0.312927	0.312912	1.28354e-05
17	0.312897	0.312912	0.312904	-1.45349e-05
18	0.312904	0.312912	0.312908	-8.4977e-07
19	0.312908	0.312912	0.31291	5.99279e-06
20	0.312908	0.31291	0.312909	2.57151e-06
21	0.312908	0.312909	0.312909	8.60869e-07
22	0.312908	0.312909	0.312908	5.54898e-09
23	0.312908	0.312908	0.312908	-4.22111e-07
24	0.312908	0.312908	0.312908	-2.08281e-07
25	0.312908	0.312908	0.312908	-1.01366e-07
26	0.312908	0.312908	0.312908	-4.79085e-08
27	0.312908	0.312908	0.312908	-2.11798e-08
28	0.312908	0.312908	0.312908	-7.81538e-09
29	0.312908	0.312908	0.312908	-1.1332e-09

Approximate root = 0.312908
Total iterations = 29