fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5.  
  6. double a = 1, b = 2, c, eps = 1e-9;
  7.  
  8. while (b - a > eps) {
  9. // (1) find middle point
  10. c = (a + b) / 2;
  11.  
  12. // (2) calculate the function values
  13. double fa = a * a * a - a - 2;
  14. double fb = b * b * b - b - 2;
  15. double fc = c * c * c - c - 2;
  16.  
  17. // (3) determine which way to go
  18. // if ((fa > 0 && fc < 0 ) || (fa < 0 && fc > 0))
  19. if (fa * fc < 0) {
  20. b = c;
  21. } else {
  22. a = c;
  23. }
  24. }
  25.  
  26. cout << "root ~ " << c << endl;
  27. cout << "error ~ " << c * c * c - c - 2 << endl;
  28.  
  29. return 0;
  30. }
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
root ~ 1.52138
error ~ -2.10862e-09