snippet8.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // (C) Copyright Gennadiy Rozental 2001-2015.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE_1_0.txt or copy at
  4. // http://www.boost.org/LICENSE_1_0.txt)
  5. //
  6. // See http://www.boost.org/libs/test for the library home page.
  7. //
  8. //[snippet8
  9. double find_root( double (*f)(double),
  10. double low_guess,
  11. double high_guess,
  12. std::vector<double>& steps,
  13. double tolerance )
  14. {
  15. double solution;
  16. bool converged = false;
  17. while(not converged)
  18. {
  19. double temp = (low_guess + high_guess) / 2.0;
  20. steps.push_back( temp );
  21. double f_temp = f(temp);
  22. double f_low = f(low_guess);
  23. if(abs(f_temp) < tolerance)
  24. {
  25. solution = temp;
  26. converged = true;
  27. }
  28. else if(f_temp / abs(f_temp) == f_low / abs(f_low))
  29. {
  30. low_guess = temp;
  31. converged = false;
  32. }
  33. else
  34. {
  35. high_guess = temp;
  36. converged = false;
  37. }
  38. }
  39. return solution;
  40. }
  41. //]