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;
  11. double tol = 0.0001;
  12. cout << "Iter\t" << "Root\n";
  13.  
  14. // Root lies between [0..1]
  15. double a = 0, b = 1;
  16. double c, prev = 0;
  17. do {
  18. c = (a * f(b) - b * f(a)) / (f(b) - f(a));
  19. cout << ++iter << "\t" << c << endl;
  20. if (fabs(f(c)) < tol) {
  21. break;
  22. }
  23.  
  24. if (f(c) * f(a) < 0) {
  25. b = c;
  26. } else {
  27. a = c;
  28. }
  29. if (fabs(c - prev) < tol) {
  30. break;
  31. }
  32.  
  33. prev = c;
  34.  
  35. } while (fabs(b - a) > tol);
  36.  
  37. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Iter	Root
1	0.578085
2	0.605959
3	0.607057
4	0.6071