fork download
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. // Define the function whose root is to be determined
  6. double f(double x) {
  7. return x * x * x + x * x - 1; // Example function
  8. }
  9.  
  10. int main() {
  11. double x0, x1, x2, f0, f1, f2;
  12. int iteration = 1, maxIter = 20;
  13. double E = 0.0001; // desired accuracy
  14.  
  15. // Input initial guesses
  16. cout << "Enter the value of x0: ";
  17. cin >> x0;
  18. cout << "Enter the value of x1: ";
  19. cin >> x1;
  20.  
  21. cout << "\nIteration\tx0\t\tx1\t\tx2\t\tf0\t\tf1\t\tf2\n";
  22. cout << "-----------------------------------------------------------------------------\n";
  23.  
  24. do {
  25. f0 = f(x0);
  26. f1 = f(x1);
  27.  
  28. if (f1 - f0 == 0) {
  29. cout << "Division by zero error!";
  30. return 1;
  31. }
  32.  
  33. x2 = (x0 * f1 - x1 * f0) / (f1 - f0);
  34. f2 = f(x2);
  35.  
  36. cout << iteration << "\t\t"
  37. << x0 << "\t"
  38. << x1 << "\t"
  39. << x2 << "\t"
  40. << f0 << "\t"
  41. << f1 << "\t"
  42. << f2 << endl;
  43.  
  44. x0 = x1;
  45. x1 = x2;
  46.  
  47. iteration++;
  48.  
  49. if (fabs(f2) < E)
  50. break;
  51.  
  52. } while (iteration <= maxIter);
  53.  
  54. cout << "\nApproximate root = " << x2 << endl;
  55.  
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0.01s 5316KB
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