fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. // f(x) = 3x - cos(x) - 1
  4. double f(double x) {
  5. return 3*x - cos(x) - 1;
  6. }
  7.  
  8. signed main() {
  9. ios_base::sync_with_stdio(false); cin.tie(NULL);
  10. int iter = 0, max_iter = 100;
  11. double tol = 0.0001;
  12. cout << "Iter\tRoot\n";
  13. // initial guesses
  14. double x0 = 0, x1 = 1, x2;
  15. do {
  16. x2 = (x0*f(x1) - x1*f(x0)) / (f(x1) - f(x0));
  17. cout << ++iter << "\t" << x2 << endl;
  18. if (fabs(f(x2)) < tol) {
  19. break;
  20. }
  21. x0 = x1;
  22. x1 = x2;
  23. if (iter > max_iter) {
  24. cout << "Max iterations reached\n";
  25. break;
  26. }
  27. } while (fabs(x1 - x0) > tol);
  28. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
Iter	Root
1	0.578085
2	0.605959
3	0.607106