fork download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. double f(double x) {
  6. return x*x*x + x*x - 1;
  7. }
  8.  
  9. int main() {
  10. double x0, x1, x2, f0, f1, f2;
  11. int iteration = 1, maxIter = 20;
  12. double E = 0.0001;
  13.  
  14. cout << "Enter the value of x0: ";
  15. cin >> x0;
  16. cout << "Enter the value of x1: ";
  17. cin >> x1;
  18.  
  19. cout << "\nIteration\tx0\t\tx1\t\tx2\t\tf0\t\tf1\t\tf2\n";
  20. cout << "-----------------------------------------------------------------------------\n";
  21.  
  22. do {
  23. f0 = f(x0);
  24. f1 = f(x1);
  25.  
  26. if (f1 - f0 == 0) {
  27. cout << "Division by zero error!";
  28. return 1;
  29. }
  30.  
  31. x2 = (x0 * f1 - x1 * f0) / (f1 - f0);
  32. f2 = f(x2);
  33.  
  34. cout << iteration << "\t\t"
  35. << x0 << "\t"
  36. << x1 << "\t"
  37. << x2 << "\t"
  38. << f0 << "\t"
  39. << f1 << "\t"
  40. << f2 << endl;
  41.  
  42. x0 = x1;
  43. x1 = x2;
  44.  
  45. iteration++;
  46.  
  47. if (fabs(f2) < E)
  48. break;
  49.  
  50. } while (iteration <= maxIter);
  51.  
  52. cout << "\nApproximate root = " << x2 << endl;
  53.  
  54. return 0;
  55. }
  56.  
Success #stdin #stdout 0s 5320KB
stdin
-1
3
stdout
Enter the value of x0: Enter the value of x1: 
Iteration	x0		x1		x2		f0		f1		f2
-----------------------------------------------------------------------------
1		-1	3	-0.888889	-1	35	-0.912209
2		3	-0.888889	-0.790107	35	-0.912209	-0.86897
3		-0.888889	-0.790107	1.19514	-0.912209	-0.86897	2.13545
4		-0.790107	1.19514	-0.215913	-0.86897	2.13545	-0.963447
5		1.19514	-0.215913	0.222783	2.13545	-0.963447	-0.93931
6		-0.215913	0.222783	17.2951	-0.963447	-0.93931	5471.41
7		0.222783	17.2951	0.225714	-0.93931	5471.41	-0.937554
8		17.2951	0.225714	0.228638	5471.41	-0.937554	-0.935772
9		0.225714	0.228638	1.76475	-0.937554	-0.935772	7.61042
10		0.228638	1.76475	0.396836	-0.935772	7.61042	-0.780027
11		1.76475	0.396836	0.524006	7.61042	-0.780027	-0.581534
12		0.396836	0.524006	0.896582	-0.780027	-0.581534	0.524585
13		0.524006	0.896582	0.719885	-0.581534	0.524585	-0.108695
14		0.896582	0.719885	0.750213	0.524585	-0.108695	-0.0149449
15		0.719885	0.750213	0.755048	-0.108695	-0.0149449	0.000548269
16		0.750213	0.755048	0.754877	-0.0149449	0.000548269	-2.60117e-06

Approximate root = 0.754877