fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. //f(x) = 3x - cosx - 1
  4. double f(double x) {
  5. return 3*x - cos(x) - 1;
  6. }
  7. double fdash(double x) {
  8. return 3 + sin(x);
  9. }
  10.  
  11. signed main() {
  12. ios_base::sync_with_stdio(false); cin.tie(NULL);
  13. freopen("Error.txt", "w", stderr);
  14. int iter = 0;
  15. double tol = 0.0001;
  16. double x0 = 0;
  17. double diff = 1e9;
  18. cout << "Iter\t" << "Root\n";
  19. do {
  20. double root = x0 - (f(x0) / fdash(x0));
  21. cout << ++iter << "\t" << root << endl;
  22. diff = fabs(root - x0);
  23. x0 = root;
  24. }while (diff > tol);
  25. }
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
Iter	Root
1	0.666667
2	0.607493
3	0.607102
4	0.607102