fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. double computeFunction(double x) {
  6. return x * x * x - 4.0;
  7. }
  8.  
  9. int main() {
  10. double a, b, c, f_a, f_b, f_c, tolerance = 0.0001, root;
  11. int iteration = 0;
  12.  
  13.  
  14. while (true) {
  15. cout << "Enter two initial guesses: ";
  16. cin >> a >> b;
  17.  
  18. f_a = computeFunction(a);
  19. f_b = computeFunction(b);
  20.  
  21. cout << "f(a) = " << f_a << ", f(b) = " << f_b << endl;
  22.  
  23. if (f_a * f_b < 0) break;
  24. else cout << "Invalid interval. Try again.\n";
  25. }
  26.  
  27.  
  28. c = (a - f_a * (b - a)) / (f_b - f_a);
  29. f_c = computeFunction(c);
  30.  
  31. if (f_c == 0.0) {
  32. cout << fixed << setprecision(8);
  33. cout << "Exact root found: " << c << endl;
  34. return 0;
  35. }
  36.  
  37.  
  38. cout << "Iter\tc\t\ta\t\tb\t\tf(c)\t\tf(a)\t\tf(b)\n";
  39. cout << iteration << "\t" << fixed << setprecision(8)
  40. << c << "\t" << a << "\t" << b << "\t"
  41. << f_c << "\t" << f_a << "\t" << f_b << endl;
  42.  
  43. while (true) {
  44. c = (a - f_a * (b - a)) / (f_b - f_a);
  45. f_c = computeFunction(c);
  46. iteration++;
  47.  
  48. cout << iteration << "\t" << fixed << setprecision(8)
  49. << c << "\t" << a << "\t" << b << "\t"
  50. << f_c << "\t" << f_a << "\t" << f_b << endl;
  51.  
  52. if (fabs((b - a) / b) < tolerance || iteration > 8) {
  53. break;
  54. }
  55.  
  56. if (f_a * f_c < 0) {
  57. b = c;
  58. f_b = f_c;
  59. } else {
  60. a = c;
  61. f_a = f_c;
  62. }
  63.  
  64. root = c;
  65. }
  66.  
  67. cout << fixed << setprecision(8);
  68. cout << "Approximate root = " << root << endl;
  69. return 0;
  70. }
Success #stdin #stdout 0.01s 5316KB
stdin
-1
3
stdout
Enter two initial guesses: f(a) = -5, f(b) = 23
Iter	c		a		b		f(c)		f(a)		f(b)
0	0.67857143	-1.00000000	3.00000000	-3.68754555	-5.00000000	23.00000000
1	0.67857143	-1.00000000	3.00000000	-3.68754555	-5.00000000	23.00000000
2	0.34618939	0.67857143	3.00000000	-3.95851021	-3.68754555	23.00000000
3	0.40251949	0.34618939	3.00000000	-3.93478301	-3.95851021	23.00000000
4	0.39439864	0.40251949	3.00000000	-3.93865118	-3.93478301	23.00000000
5	0.39560086	0.39439864	3.00000000	-3.93808845	-3.93865118	23.00000000
6	0.39542357	0.39560086	3.00000000	-3.93817165	-3.93808845	23.00000000
7	0.39544973	0.39542357	3.00000000	-3.93815938	-3.93817165	23.00000000
8	0.39544587	0.39544973	3.00000000	-3.93816119	-3.93815938	23.00000000
9	0.39544644	0.39544587	3.00000000	-3.93816092	-3.93816119	23.00000000
Approximate root = 0.39544587