fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. double evaluate(double x) {
  6. return x * x * x - 4.0;
  7. }
  8.  
  9. int main() {
  10. double prev, curr, next, f_prev, f_curr, f_next, tolerance = 0.0001, approxRoot;
  11. int iteration = 0;
  12.  
  13. cout << "Enter two initial guesses: ";
  14. cin >> prev >> curr;
  15.  
  16. f_prev = evaluate(prev);
  17. f_curr = evaluate(curr);
  18.  
  19. cout << "f(x1) = " << f_prev << ", f(x2) = " << f_curr << endl;
  20.  
  21.  
  22. next = (f_curr * prev - f_prev * curr) / (f_curr - f_prev);
  23.  
  24. cout << "Iter\tNext\t\tPrev\t\tCurr\t\tf(Next)\tf(Prev)\tf(Curr)\n";
  25. cout << iteration << "\t" << fixed << setprecision(8)
  26. << next << "\t" << prev << "\t" << curr << "\t"
  27. << evaluate(next) << "\t" << f_prev << "\t" << f_curr << endl;
  28.  
  29. while (true) {
  30. f_prev = evaluate(prev);
  31. f_curr = evaluate(curr);
  32. next = (f_curr * prev - f_prev * curr) / (f_curr - f_prev);
  33. f_next = evaluate(next);
  34.  
  35. iteration++;
  36. cout << iteration << "\t" << fixed << setprecision(8)
  37. << next << "\t" << prev << "\t" << curr << "\t"
  38. << f_next << "\t" << f_prev << "\t" << f_curr << endl;
  39.  
  40. if (fabs((next - curr) / next) < tolerance || iteration > 8)
  41. break;
  42.  
  43. prev = curr;
  44. curr = next;
  45.  
  46. approxRoot = next;
  47. }
  48.  
  49. cout << fixed << setprecision(8);
  50. cout << "Approximate root = " << approxRoot << endl;
  51.  
  52. return 0;
  53. }
  54.  
Success #stdin #stdout 0.01s 5284KB
stdin
-1
2
stdout
Enter two initial guesses: f(x1) = -5, f(x2) = 4
Iter	Next		Prev		Curr		f(Next)	f(Prev)	f(Curr)
0	0.66666667	-1.00000000	2.00000000	-3.70370370	-5.00000000	4.00000000
1	0.66666667	-1.00000000	2.00000000	-3.70370370	-5.00000000	4.00000000
2	1.30769231	2.00000000	0.66666667	-1.76376878	4.00000000	-3.70370370
3	1.89050619	0.66666667	1.30769231	2.75669495	-3.70370370	-1.76376878
4	1.53509131	1.30769231	1.89050619	-0.38254916	-1.76376878	2.75669495
5	1.57840226	1.89050619	1.53509131	-0.06764167	2.75669495	-0.38254916
6	1.58770539	1.53509131	1.57840226	0.00230112	-0.38254916	-0.06764167
7	1.58739932	1.57840226	1.58770539	-0.00001309	-0.06764167	0.00230112
8	1.58740105	1.58770539	1.58739932	-0.00000000	0.00230112	-0.00001309
Approximate root = 1.58739932