1 // (C) Copyright John Maddock 2006.
2 // Use, modification and distribution are subject to the
3 // Boost Software License, Version 1.0. (See accompanying file
4 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 #ifndef BOOST_MATH_TOOLS_SOLVE_ROOT_HPP
7 #define BOOST_MATH_TOOLS_SOLVE_ROOT_HPP
13 #include <boost/math/tools/precision.hpp>
14 #include <boost/math/policies/error_handling.hpp>
15 #include <boost/math/tools/config.hpp>
16 #include <boost/math/special_functions/sign.hpp>
17 #include <boost/cstdint.hpp>
20 #ifdef BOOST_MATH_LOG_ROOT_ITERATIONS
21 # define BOOST_MATH_LOGGER_INCLUDE <boost/math/tools/iteration_logger.hpp>
22 # include BOOST_MATH_LOGGER_INCLUDE
23 # undef BOOST_MATH_LOGGER_INCLUDE
25 # define BOOST_MATH_LOG_COUNT(count)
28 namespace boost{ namespace math{ namespace tools{
36 eps = 4 * tools::epsilon<T>();
38 eps_tolerance(unsigned bits)
41 eps = (std::max)(T(ldexp(1.0F, 1-bits)), T(4 * tools::epsilon<T>()));
43 bool operator()(const T& a, const T& b)
46 return fabs(a - b) <= (eps * (std::min)(fabs(a), fabs(b)));
56 bool operator()(const T& a, const T& b)
59 return floor(a) == floor(b);
67 bool operator()(const T& a, const T& b)
70 return ceil(a) == ceil(b);
74 struct equal_nearest_integer
76 equal_nearest_integer(){}
78 bool operator()(const T& a, const T& b)
81 return floor(a + 0.5f) == floor(b + 0.5f);
87 template <class F, class T>
88 void bracket(F f, T& a, T& b, T c, T& fa, T& fb, T& d, T& fd)
91 // Given a point c inside the existing enclosing interval
92 // [a, b] sets a = c if f(c) == 0, otherwise finds the new
93 // enclosing interval: either [a, c] or [c, b] and sets
94 // d and fd to the point that has just been removed from
95 // the interval. In other words d is the third best guess
98 BOOST_MATH_STD_USING // For ADL of std math functions
99 T tol = tools::epsilon<T>() * 2;
101 // If the interval [a,b] is very small, or if c is too close
102 // to one end of the interval then we need to adjust the
103 // location of c accordingly:
105 if((b - a) < 2 * tol * a)
109 else if(c <= a + fabs(a) * tol)
111 c = a + fabs(a) * tol;
113 else if(c >= b - fabs(b) * tol)
115 c = b - fabs(b) * tol;
118 // OK, lets invoke f(c):
122 // if we have a zero then we have an exact solution to the root:
133 // Non-zero fc, update the interval:
135 if(boost::math::sign(fa) * boost::math::sign(fc) < 0)
152 inline T safe_div(T num, T denom, T r)
155 // return num / denom without overflow,
156 // return r if overflow would occur.
158 BOOST_MATH_STD_USING // For ADL of std math functions
162 if(fabs(denom * tools::max_value<T>()) <= fabs(num))
169 inline T secant_interpolate(const T& a, const T& b, const T& fa, const T& fb)
172 // Performs standard secant interpolation of [a,b] given
173 // function evaluations f(a) and f(b). Performs a bisection
174 // if secant interpolation would leave us very close to either
175 // a or b. Rationale: we only call this function when at least
176 // one other form of interpolation has already failed, so we know
177 // that the function is unlikely to be smooth with a root very
180 BOOST_MATH_STD_USING // For ADL of std math functions
182 T tol = tools::epsilon<T>() * 5;
183 T c = a - (fa / (fb - fa)) * (b - a);
184 if((c <= a + fabs(a) * tol) || (c >= b - fabs(b) * tol))
190 T quadratic_interpolate(const T& a, const T& b, T const& d,
191 const T& fa, const T& fb, T const& fd,
195 // Performs quadratic interpolation to determine the next point,
196 // takes count Newton steps to find the location of the
197 // quadratic polynomial.
199 // Point d must lie outside of the interval [a,b], it is the third
200 // best approximation to the root, after a and b.
202 // Note: this does not guarantee to find a root
203 // inside [a, b], so we fall back to a secant step should
204 // the result be out of range.
206 // Start by obtaining the coefficients of the quadratic polynomial:
208 T B = safe_div(T(fb - fa), T(b - a), tools::max_value<T>());
209 T A = safe_div(T(fd - fb), T(d - b), tools::max_value<T>());
210 A = safe_div(T(A - B), T(d - a), T(0));
214 // failure to determine coefficients, try a secant step:
215 return secant_interpolate(a, b, fa, fb);
218 // Determine the starting point of the Newton steps:
221 if(boost::math::sign(A) * boost::math::sign(fa) > 0)
230 // Take the Newton steps:
232 for(unsigned i = 1; i <= count; ++i)
234 //c -= safe_div(B * c, (B + A * (2 * c - a - b)), 1 + c - a);
235 c -= safe_div(T(fa+(B+A*(c-b))*(c-a)), T(B + A * (2 * c - a - b)), T(1 + c - a));
237 if((c <= a) || (c >= b))
239 // Oops, failure, try a secant step:
240 c = secant_interpolate(a, b, fa, fb);
246 T cubic_interpolate(const T& a, const T& b, const T& d,
247 const T& e, const T& fa, const T& fb,
248 const T& fd, const T& fe)
251 // Uses inverse cubic interpolation of f(x) at points
252 // [a,b,d,e] to obtain an approximate root of f(x).
253 // Points d and e lie outside the interval [a,b]
254 // and are the third and forth best approximations
255 // to the root that we have found so far.
257 // Note: this does not guarantee to find a root
258 // inside [a, b], so we fall back to quadratic
259 // interpolation in case of an erroneous result.
261 BOOST_MATH_INSTRUMENT_CODE(" a = " << a << " b = " << b
262 << " d = " << d << " e = " << e << " fa = " << fa << " fb = " << fb
263 << " fd = " << fd << " fe = " << fe);
264 T q11 = (d - e) * fd / (fe - fd);
265 T q21 = (b - d) * fb / (fd - fb);
266 T q31 = (a - b) * fa / (fb - fa);
267 T d21 = (b - d) * fd / (fd - fb);
268 T d31 = (a - b) * fb / (fb - fa);
269 BOOST_MATH_INSTRUMENT_CODE(
270 "q11 = " << q11 << " q21 = " << q21 << " q31 = " << q31
271 << " d21 = " << d21 << " d31 = " << d31);
272 T q22 = (d21 - q11) * fb / (fe - fb);
273 T q32 = (d31 - q21) * fa / (fd - fa);
274 T d32 = (d31 - q21) * fd / (fd - fa);
275 T q33 = (d32 - q22) * fa / (fe - fa);
276 T c = q31 + q32 + q33 + a;
277 BOOST_MATH_INSTRUMENT_CODE(
278 "q22 = " << q22 << " q32 = " << q32 << " d32 = " << d32
279 << " q33 = " << q33 << " c = " << c);
281 if((c <= a) || (c >= b))
283 // Out of bounds step, fall back to quadratic interpolation:
284 c = quadratic_interpolate(a, b, d, fa, fb, fd, 3);
285 BOOST_MATH_INSTRUMENT_CODE(
286 "Out of bounds interpolation, falling back to quadratic interpolation. c = " << c);
292 } // namespace detail
294 template <class F, class T, class Tol, class Policy>
295 std::pair<T, T> toms748_solve(F f, const T& ax, const T& bx, const T& fax, const T& fbx, Tol tol, boost::uintmax_t& max_iter, const Policy& pol)
298 // Main entry point and logic for Toms Algorithm 748
301 BOOST_MATH_STD_USING // For ADL of std math functions
303 static const char* function = "boost::math::tools::toms748_solve<%1%>";
305 boost::uintmax_t count = max_iter;
306 T a, b, fa, fb, c, u, fu, a0, b0, d, fd, e, fe;
307 static const T mu = 0.5f;
309 // initialise a, b and fa, fb:
313 return boost::math::detail::pair_from_single(policies::raise_domain_error(
315 "Parameters a and b out of order: a=%1%", a, pol));
319 if(tol(a, b) || (fa == 0) || (fb == 0))
326 return std::make_pair(a, b);
329 if(boost::math::sign(fa) * boost::math::sign(fb) > 0)
330 return boost::math::detail::pair_from_single(policies::raise_domain_error(
332 "Parameters a and b do not bracket the root: a=%1%", a, pol));
333 // dummy value for fd, e and fe:
339 // On the first step we take a secant step:
341 c = detail::secant_interpolate(a, b, fa, fb);
342 detail::bracket(f, a, b, c, fa, fb, d, fd);
344 BOOST_MATH_INSTRUMENT_CODE(" a = " << a << " b = " << b);
346 if(count && (fa != 0) && !tol(a, b))
349 // On the second step we take a quadratic interpolation:
351 c = detail::quadratic_interpolate(a, b, d, fa, fb, fd, 2);
354 detail::bracket(f, a, b, c, fa, fb, d, fd);
356 BOOST_MATH_INSTRUMENT_CODE(" a = " << a << " b = " << b);
360 while(count && (fa != 0) && !tol(a, b))
362 // save our brackets:
366 // Starting with the third step taken
367 // we can use either quadratic or cubic interpolation.
368 // Cubic interpolation requires that all four function values
369 // fa, fb, fd, and fe are distinct, should that not be the case
370 // then variable prof will get set to true, and we'll end up
371 // taking a quadratic step instead.
373 T min_diff = tools::min_value<T>() * 32;
374 bool prof = (fabs(fa - fb) < min_diff) || (fabs(fa - fd) < min_diff) || (fabs(fa - fe) < min_diff) || (fabs(fb - fd) < min_diff) || (fabs(fb - fe) < min_diff) || (fabs(fd - fe) < min_diff);
377 c = detail::quadratic_interpolate(a, b, d, fa, fb, fd, 2);
378 BOOST_MATH_INSTRUMENT_CODE("Can't take cubic step!!!!");
382 c = detail::cubic_interpolate(a, b, d, e, fa, fb, fd, fe);
385 // re-bracket, and check for termination:
389 detail::bracket(f, a, b, c, fa, fb, d, fd);
390 if((0 == --count) || (fa == 0) || tol(a, b))
392 BOOST_MATH_INSTRUMENT_CODE(" a = " << a << " b = " << b);
394 // Now another interpolated step:
396 prof = (fabs(fa - fb) < min_diff) || (fabs(fa - fd) < min_diff) || (fabs(fa - fe) < min_diff) || (fabs(fb - fd) < min_diff) || (fabs(fb - fe) < min_diff) || (fabs(fd - fe) < min_diff);
399 c = detail::quadratic_interpolate(a, b, d, fa, fb, fd, 3);
400 BOOST_MATH_INSTRUMENT_CODE("Can't take cubic step!!!!");
404 c = detail::cubic_interpolate(a, b, d, e, fa, fb, fd, fe);
407 // Bracket again, and check termination condition, update e:
409 detail::bracket(f, a, b, c, fa, fb, d, fd);
410 if((0 == --count) || (fa == 0) || tol(a, b))
412 BOOST_MATH_INSTRUMENT_CODE(" a = " << a << " b = " << b);
414 // Now we take a double-length secant step:
416 if(fabs(fa) < fabs(fb))
426 c = u - 2 * (fu / (fb - fa)) * (b - a);
427 if(fabs(c - u) > (b - a) / 2)
432 // Bracket again, and check termination condition:
436 detail::bracket(f, a, b, c, fa, fb, d, fd);
437 BOOST_MATH_INSTRUMENT_CODE(" a = " << a << " b = " << b);
438 BOOST_MATH_INSTRUMENT_CODE(" tol = " << T((fabs(a) - fabs(b)) / fabs(a)));
439 if((0 == --count) || (fa == 0) || tol(a, b))
442 // And finally... check to see if an additional bisection step is
443 // to be taken, we do this if we're not converging fast enough:
445 if((b - a) < mu * (b0 - a0))
448 // bracket again on a bisection:
452 detail::bracket(f, a, b, T(a + (b - a) / 2), fa, fb, d, fd);
454 BOOST_MATH_INSTRUMENT_CODE("Not converging: Taking a bisection!!!!");
455 BOOST_MATH_INSTRUMENT_CODE(" a = " << a << " b = " << b);
467 BOOST_MATH_LOG_COUNT(max_iter)
468 return std::make_pair(a, b);
471 template <class F, class T, class Tol>
472 inline std::pair<T, T> toms748_solve(F f, const T& ax, const T& bx, const T& fax, const T& fbx, Tol tol, boost::uintmax_t& max_iter)
474 return toms748_solve(f, ax, bx, fax, fbx, tol, max_iter, policies::policy<>());
477 template <class F, class T, class Tol, class Policy>
478 inline std::pair<T, T> toms748_solve(F f, const T& ax, const T& bx, Tol tol, boost::uintmax_t& max_iter, const Policy& pol)
481 std::pair<T, T> r = toms748_solve(f, ax, bx, f(ax), f(bx), tol, max_iter, pol);
486 template <class F, class T, class Tol>
487 inline std::pair<T, T> toms748_solve(F f, const T& ax, const T& bx, Tol tol, boost::uintmax_t& max_iter)
489 return toms748_solve(f, ax, bx, tol, max_iter, policies::policy<>());
492 template <class F, class T, class Tol, class Policy>
493 std::pair<T, T> bracket_and_solve_root(F f, const T& guess, T factor, bool rising, Tol tol, boost::uintmax_t& max_iter, const Policy& pol)
496 static const char* function = "boost::math::tools::bracket_and_solve_root<%1%>";
498 // Set up inital brackets:
505 // Set up invocation count:
507 boost::uintmax_t count = max_iter - 1;
511 if((fa < 0) == (guess < 0 ? !rising : rising))
514 // Zero is to the right of b, so walk upwards
517 while((boost::math::sign)(fb) == (boost::math::sign)(fa))
520 return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function, "Unable to bracket root, last nearest value was %1%", b, pol));
522 // Heuristic: normally it's best not to increase the step sizes as we'll just end up
523 // with a really wide range to search for the root. However, if the initial guess was *really*
524 // bad then we need to speed up the search otherwise we'll take forever if we're orders of
525 // magnitude out. This happens most often if the guess is a small value (say 1) and the result
526 // we're looking for is close to std::numeric_limits<T>::min().
528 if((max_iter - count) % step == 0)
531 if(step > 1) step /= 2;
534 // Now go ahead and move our guess by "factor":
541 BOOST_MATH_INSTRUMENT_CODE("a = " << a << " b = " << b << " fa = " << fa << " fb = " << fb << " count = " << count);
547 // Zero is to the left of a, so walk downwards
550 while((boost::math::sign)(fb) == (boost::math::sign)(fa))
552 if(fabs(a) < tools::min_value<T>())
554 // Escape route just in case the answer is zero!
557 return a > 0 ? std::make_pair(T(0), T(a)) : std::make_pair(T(a), T(0));
560 return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function, "Unable to bracket root, last nearest value was %1%", a, pol));
562 // Heuristic: normally it's best not to increase the step sizes as we'll just end up
563 // with a really wide range to search for the root. However, if the initial guess was *really*
564 // bad then we need to speed up the search otherwise we'll take forever if we're orders of
565 // magnitude out. This happens most often if the guess is a small value (say 1) and the result
566 // we're looking for is close to std::numeric_limits<T>::min().
568 if((max_iter - count) % step == 0)
571 if(step > 1) step /= 2;
574 // Now go ahead and move are guess by "factor":
581 BOOST_MATH_INSTRUMENT_CODE("a = " << a << " b = " << b << " fa = " << fa << " fb = " << fb << " count = " << count);
586 std::pair<T, T> r = toms748_solve(
596 BOOST_MATH_INSTRUMENT_CODE("max_iter = " << max_iter << " count = " << count);
597 BOOST_MATH_LOG_COUNT(max_iter)
601 template <class F, class T, class Tol>
602 inline std::pair<T, T> bracket_and_solve_root(F f, const T& guess, const T& factor, bool rising, Tol tol, boost::uintmax_t& max_iter)
604 return bracket_and_solve_root(f, guess, factor, rising, tol, max_iter, policies::policy<>());
612 #endif // BOOST_MATH_TOOLS_SOLVE_ROOT_HPP