fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. double f(double x) {
  5. return ((3 * x) * x) * x - 4;
  6. }
  7.  
  8. int main() {
  9. double x1, x2, x3, f1, f2, E;
  10. int i = 1;
  11.  
  12. cout << "Enter two initial points x1 and x2: ";
  13. cin >> x1 >> x2;
  14. cout << "Enter required accuracy (E): ";
  15. cin >> E;
  16.  
  17. f1 = f(x1);
  18. f2 = f(x2);
  19.  
  20. cout << fixed << setprecision(6);
  21. cout << "Iteration\tX1\t\tX2\t\tX3\t\tf(X1)\t\tf(X2)" << endl;
  22.  
  23. do {
  24. x3 = (f2 * x1 - f1 * x2) / (f2 - f1);
  25.  
  26. cout << i << "\t\t" << x1 << "\t" << x2 << "\t" << x3
  27. << "\t" << f1 << "\t" << f2 << endl;
  28.  
  29. if (fabs((x3 - x2) / x3) <= E) {
  30. cout << "\nRoot found at x = " << x3 << " after " << i << " iterations." << endl;
  31. break;
  32. }
  33.  
  34. x1 = x2;
  35. f1 = f2;
  36. x2 = x3;
  37. f2 = f(x3);
  38. i++;
  39.  
  40. } while (true);
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0.01s 5288KB
stdin
1 2
0.00001
stdout
Enter two initial points x1 and x2: Enter required accuracy (E): Iteration	X1		X2		X3		f(X1)		f(X2)
1		1.000000	2.000000	1.047619	-1.000000	20.000000
2		2.000000	1.047619	1.073140	20.000000	-0.550696
3		1.047619	1.073140	1.102035	-0.550696	-0.292421
4		1.073140	1.102035	1.100607	-0.292421	0.015202
5		1.102035	1.100607	1.100642	0.015202	-0.000385
6		1.100607	1.100642	1.100642	-0.000385	-0.000000

Root found at x = 1.100642 after 6 iterations.