fork download
  1. #include <iostream> //id= 240242103
  2. #include <cmath>
  3. #include <iomanip>
  4. using namespace std;
  5.  
  6. double f(double x) {
  7. return x*x*x - 4; // f(x) = x^3 - 4
  8. }
  9.  
  10. int main() {
  11. double x0 = 1, x1 = 3, x2, f0, f1, f2, Ea, prev_x2;
  12. int iterations = 3;
  13.  
  14. cout << fixed << setprecision(6);
  15. cout << "Iteration x0 x1 x2 f0 f1 f2 Ea(%)\n";
  16. cout << "----------------------------------------------------------------------------\n";
  17.  
  18. for (int i = 1; i <= iterations; i++) {
  19. f0 = f(x0);
  20. f1 = f(x1);
  21.  
  22. // False Position formula
  23. x2 = x0 - f0*(x1 - x0)/(f1 - f0);
  24. f2 = f(x2);
  25.  
  26. if (i == 1)
  27. Ea = 0;
  28. else
  29. Ea = fabs((x2 - prev_x2)/x2)*100;
  30.  
  31. cout << i << "\t" << x0 << "\t" << x1 << "\t" << x2
  32. << "\t" << f0 << "\t" << f1 << "\t" << f2 << "\t" << Ea << endl;
  33.  
  34. // Update interval according to algorithm
  35. if (f0*f2 < 0)
  36. x1 = x2;
  37. else
  38. x0 = x2;
  39.  
  40. prev_x2 = x2; // save x2 for next iteration
  41. }
  42.  
  43. cout << "\nApproximate root after " << iterations << " iterations = " << x2 << endl;
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0.01s 5312KB
stdin
Standard input is empty
stdout
Iteration  x0        x1        x2        f0        f1        f2        Ea(%)
----------------------------------------------------------------------------
1	1.000000	3.000000	1.230769	-3.000000	23.000000	-2.135640	0.000000
2	1.230769	3.000000	1.381091	-2.135640	23.000000	-1.365689	10.884291
3	1.381091	3.000000	1.471831	-1.365689	23.000000	-0.811596	6.165064

Approximate root after 3 iterations = 1.471831