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 0.01s 5320KB
stdin
-1
-2
stdout
Enter the value of x0: Enter the value of x1: 
Iteration	x0		x1		x2		f0		f1		f2
-----------------------------------------------------------------------------
1		-1	-2	-0.75	-1	-5	-0.859375
2		-2	-0.75	-0.490566	-5	-0.859375	-0.877402
3		-0.75	-0.490566	-13.1175	-0.859375	-0.877402	-2086.05
4		-0.490566	-13.1175	-0.485253	-0.877402	-2086.05	-0.878792
5		-13.1175	-0.485253	-0.479929	-2086.05	-0.878792	-0.880211
6		-0.485253	-0.479929	-3.78287	-0.878792	-0.880211	-40.8233
7		-0.479929	-3.78287	-0.407143	-0.880211	-40.8233	-0.901725
8		-3.78287	-0.407143	-0.330894	-40.8233	-0.901725	-0.926739
9		-0.407143	-0.330894	-3.15581	-0.901725	-0.926739	-22.4699
10		-0.330894	-3.15581	-0.209373	-0.926739	-22.4699	-0.965341
11		-3.15581	-0.209373	-0.0771073	-22.4699	-0.965341	-0.994513
12		-0.209373	-0.0771073	-4.58628	-0.965341	-0.994513	-76.4335
13		-0.0771073	-4.58628	-0.0176629	-0.994513	-76.4335	-0.999694
14		-4.58628	-0.0176629	0.0428831	-76.4335	-0.999694	-0.998082
15		-0.0176629	0.0428831	37.5454	-0.999694	-0.998082	54334.9
16		0.0428831	37.5454	0.043572	-0.998082	54334.9	-0.998019
17		37.5454	0.043572	0.0442608	54334.9	-0.998019	-0.997954
18		0.043572	0.0442608	10.704	-0.998019	-0.997954	1340
19		0.0442608	10.704	0.0521937	-0.997954	1340	-0.997134
20		10.704	0.0521937	0.0601141	1340	-0.997134	-0.996169

Approximate root = 0.0601141