roots.hpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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)
  5. #ifndef BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP
  6. #define BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP
  7. #ifdef _MSC_VER
  8. #pragma once
  9. #endif
  10. #include <boost/math/tools/complex.hpp> // test for multiprecision types in complex Newton
  11. #include <utility>
  12. #include <cmath>
  13. #include <tuple>
  14. #include <cstdint>
  15. #include <boost/math/tools/config.hpp>
  16. #include <boost/math/tools/cxx03_warn.hpp>
  17. #include <boost/math/special_functions/sign.hpp>
  18. #include <boost/math/special_functions/next.hpp>
  19. #include <boost/math/tools/toms748_solve.hpp>
  20. #include <boost/math/policies/error_handling.hpp>
  21. namespace boost {
  22. namespace math {
  23. namespace tools {
  24. namespace detail {
  25. namespace dummy {
  26. template<int n, class T>
  27. typename T::value_type get(const T&) BOOST_MATH_NOEXCEPT(T);
  28. }
  29. template <class Tuple, class T>
  30. void unpack_tuple(const Tuple& t, T& a, T& b) BOOST_MATH_NOEXCEPT(T)
  31. {
  32. using dummy::get;
  33. // Use ADL to find the right overload for get:
  34. a = get<0>(t);
  35. b = get<1>(t);
  36. }
  37. template <class Tuple, class T>
  38. void unpack_tuple(const Tuple& t, T& a, T& b, T& c) BOOST_MATH_NOEXCEPT(T)
  39. {
  40. using dummy::get;
  41. // Use ADL to find the right overload for get:
  42. a = get<0>(t);
  43. b = get<1>(t);
  44. c = get<2>(t);
  45. }
  46. template <class Tuple, class T>
  47. inline void unpack_0(const Tuple& t, T& val) BOOST_MATH_NOEXCEPT(T)
  48. {
  49. using dummy::get;
  50. // Rely on ADL to find the correct overload of get:
  51. val = get<0>(t);
  52. }
  53. template <class T, class U, class V>
  54. inline void unpack_tuple(const std::pair<T, U>& p, V& a, V& b) BOOST_MATH_NOEXCEPT(T)
  55. {
  56. a = p.first;
  57. b = p.second;
  58. }
  59. template <class T, class U, class V>
  60. inline void unpack_0(const std::pair<T, U>& p, V& a) BOOST_MATH_NOEXCEPT(T)
  61. {
  62. a = p.first;
  63. }
  64. template <class F, class T>
  65. void handle_zero_derivative(F f,
  66. T& last_f0,
  67. const T& f0,
  68. T& delta,
  69. T& result,
  70. T& guess,
  71. const T& min,
  72. const T& max) noexcept(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  73. {
  74. if (last_f0 == 0)
  75. {
  76. // this must be the first iteration, pretend that we had a
  77. // previous one at either min or max:
  78. if (result == min)
  79. {
  80. guess = max;
  81. }
  82. else
  83. {
  84. guess = min;
  85. }
  86. unpack_0(f(guess), last_f0);
  87. delta = guess - result;
  88. }
  89. if (sign(last_f0) * sign(f0) < 0)
  90. {
  91. // we've crossed over so move in opposite direction to last step:
  92. if (delta < 0)
  93. {
  94. delta = (result - min) / 2;
  95. }
  96. else
  97. {
  98. delta = (result - max) / 2;
  99. }
  100. }
  101. else
  102. {
  103. // move in same direction as last step:
  104. if (delta < 0)
  105. {
  106. delta = (result - max) / 2;
  107. }
  108. else
  109. {
  110. delta = (result - min) / 2;
  111. }
  112. }
  113. }
  114. } // namespace
  115. template <class F, class T, class Tol, class Policy>
  116. std::pair<T, T> bisect(F f, T min, T max, Tol tol, std::uintmax_t& max_iter, const Policy& pol) noexcept(policies::is_noexcept_error_policy<Policy>::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  117. {
  118. T fmin = f(min);
  119. T fmax = f(max);
  120. if (fmin == 0)
  121. {
  122. max_iter = 2;
  123. return std::make_pair(min, min);
  124. }
  125. if (fmax == 0)
  126. {
  127. max_iter = 2;
  128. return std::make_pair(max, max);
  129. }
  130. //
  131. // Error checking:
  132. //
  133. static const char* function = "boost::math::tools::bisect<%1%>";
  134. if (min >= max)
  135. {
  136. return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function,
  137. "Arguments in wrong order in boost::math::tools::bisect (first arg=%1%)", min, pol));
  138. }
  139. if (fmin * fmax >= 0)
  140. {
  141. return boost::math::detail::pair_from_single(policies::raise_evaluation_error(function,
  142. "No change of sign in boost::math::tools::bisect, either there is no root to find, or there are multiple roots in the interval (f(min) = %1%).", fmin, pol));
  143. }
  144. //
  145. // Three function invocations so far:
  146. //
  147. std::uintmax_t count = max_iter;
  148. if (count < 3)
  149. count = 0;
  150. else
  151. count -= 3;
  152. while (count && (0 == tol(min, max)))
  153. {
  154. T mid = (min + max) / 2;
  155. T fmid = f(mid);
  156. if ((mid == max) || (mid == min))
  157. break;
  158. if (fmid == 0)
  159. {
  160. min = max = mid;
  161. break;
  162. }
  163. else if (sign(fmid) * sign(fmin) < 0)
  164. {
  165. max = mid;
  166. }
  167. else
  168. {
  169. min = mid;
  170. fmin = fmid;
  171. }
  172. --count;
  173. }
  174. max_iter -= count;
  175. #ifdef BOOST_MATH_INSTRUMENT
  176. std::cout << "Bisection required " << max_iter << " iterations.\n";
  177. #endif
  178. return std::make_pair(min, max);
  179. }
  180. template <class F, class T, class Tol>
  181. inline std::pair<T, T> bisect(F f, T min, T max, Tol tol, std::uintmax_t& max_iter) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  182. {
  183. return bisect(f, min, max, tol, max_iter, policies::policy<>());
  184. }
  185. template <class F, class T, class Tol>
  186. inline std::pair<T, T> bisect(F f, T min, T max, Tol tol) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  187. {
  188. std::uintmax_t m = (std::numeric_limits<std::uintmax_t>::max)();
  189. return bisect(f, min, max, tol, m, policies::policy<>());
  190. }
  191. template <class F, class T>
  192. T newton_raphson_iterate(F f, T guess, T min, T max, int digits, std::uintmax_t& max_iter) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  193. {
  194. BOOST_MATH_STD_USING
  195. static const char* function = "boost::math::tools::newton_raphson_iterate<%1%>";
  196. if (min > max)
  197. {
  198. return policies::raise_evaluation_error(function, "Range arguments in wrong order in boost::math::tools::newton_raphson_iterate(first arg=%1%)", min, boost::math::policies::policy<>());
  199. }
  200. T f0(0), f1, last_f0(0);
  201. T result = guess;
  202. T factor = static_cast<T>(ldexp(1.0, 1 - digits));
  203. T delta = tools::max_value<T>();
  204. T delta1 = tools::max_value<T>();
  205. T delta2 = tools::max_value<T>();
  206. //
  207. // We use these to sanity check that we do actually bracket a root,
  208. // we update these to the function value when we update the endpoints
  209. // of the range. Then, provided at some point we update both endpoints
  210. // checking that max_range_f * min_range_f <= 0 verifies there is a root
  211. // to be found somewhere. Note that if there is no root, and we approach
  212. // a local minima, then the derivative will go to zero, and hence the next
  213. // step will jump out of bounds (or at least past the minima), so this
  214. // check *should* happen in pathological cases.
  215. //
  216. T max_range_f = 0;
  217. T min_range_f = 0;
  218. std::uintmax_t count(max_iter);
  219. #ifdef BOOST_MATH_INSTRUMENT
  220. std::cout << "Newton_raphson_iterate, guess = " << guess << ", min = " << min << ", max = " << max
  221. << ", digits = " << digits << ", max_iter = " << max_iter << "\n";
  222. #endif
  223. do {
  224. last_f0 = f0;
  225. delta2 = delta1;
  226. delta1 = delta;
  227. detail::unpack_tuple(f(result), f0, f1);
  228. --count;
  229. if (0 == f0)
  230. break;
  231. if (f1 == 0)
  232. {
  233. // Oops zero derivative!!!
  234. detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);
  235. }
  236. else
  237. {
  238. delta = f0 / f1;
  239. }
  240. #ifdef BOOST_MATH_INSTRUMENT
  241. std::cout << "Newton iteration " << max_iter - count << ", delta = " << delta << ", residual = " << f0 << "\n";
  242. #endif
  243. if (fabs(delta * 2) > fabs(delta2))
  244. {
  245. // Last two steps haven't converged.
  246. delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;
  247. // reset delta1/2 so we don't take this branch next time round:
  248. delta1 = 3 * delta;
  249. delta2 = 3 * delta;
  250. }
  251. guess = result;
  252. result -= delta;
  253. if (result <= min)
  254. {
  255. delta = 0.5F * (guess - min);
  256. result = guess - delta;
  257. if ((result == min) || (result == max))
  258. break;
  259. }
  260. else if (result >= max)
  261. {
  262. delta = 0.5F * (guess - max);
  263. result = guess - delta;
  264. if ((result == min) || (result == max))
  265. break;
  266. }
  267. // Update brackets:
  268. if (delta > 0)
  269. {
  270. max = guess;
  271. max_range_f = f0;
  272. }
  273. else
  274. {
  275. min = guess;
  276. min_range_f = f0;
  277. }
  278. //
  279. // Sanity check that we bracket the root:
  280. //
  281. if (max_range_f * min_range_f > 0)
  282. {
  283. return policies::raise_evaluation_error(function, "There appears to be no root to be found in boost::math::tools::newton_raphson_iterate, perhaps we have a local minima near current best guess of %1%", guess, boost::math::policies::policy<>());
  284. }
  285. }while(count && (fabs(result * factor) < fabs(delta)));
  286. max_iter -= count;
  287. #ifdef BOOST_MATH_INSTRUMENT
  288. std::cout << "Newton Raphson required " << max_iter << " iterations\n";
  289. #endif
  290. return result;
  291. }
  292. template <class F, class T>
  293. inline T newton_raphson_iterate(F f, T guess, T min, T max, int digits) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  294. {
  295. std::uintmax_t m = (std::numeric_limits<std::uintmax_t>::max)();
  296. return newton_raphson_iterate(f, guess, min, max, digits, m);
  297. }
  298. namespace detail {
  299. struct halley_step
  300. {
  301. template <class T>
  302. static T step(const T& /*x*/, const T& f0, const T& f1, const T& f2) noexcept(BOOST_MATH_IS_FLOAT(T))
  303. {
  304. using std::fabs;
  305. T denom = 2 * f0;
  306. T num = 2 * f1 - f0 * (f2 / f1);
  307. T delta;
  308. BOOST_MATH_INSTRUMENT_VARIABLE(denom);
  309. BOOST_MATH_INSTRUMENT_VARIABLE(num);
  310. if ((fabs(num) < 1) && (fabs(denom) >= fabs(num) * tools::max_value<T>()))
  311. {
  312. // possible overflow, use Newton step:
  313. delta = f0 / f1;
  314. }
  315. else
  316. delta = denom / num;
  317. return delta;
  318. }
  319. };
  320. template <class F, class T>
  321. T bracket_root_towards_min(F f, T guess, const T& f0, T& min, T& max, std::uintmax_t& count) noexcept(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())));
  322. template <class F, class T>
  323. T bracket_root_towards_max(F f, T guess, const T& f0, T& min, T& max, std::uintmax_t& count) noexcept(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  324. {
  325. using std::fabs;
  326. using std::ldexp;
  327. using std::abs;
  328. using std::frexp;
  329. if(count < 2)
  330. return guess - (max + min) / 2; // Not enough counts left to do anything!!
  331. //
  332. // Move guess towards max until we bracket the root, updating min and max as we go:
  333. //
  334. int e;
  335. frexp(max / guess, &e);
  336. e = abs(e);
  337. T guess0 = guess;
  338. T multiplier = e < 64 ? static_cast<T>(2) : static_cast<T>(ldexp(T(1), e / 32));
  339. T f_current = f0;
  340. if (fabs(min) < fabs(max))
  341. {
  342. while (--count && ((f_current < 0) == (f0 < 0)))
  343. {
  344. min = guess;
  345. guess *= multiplier;
  346. if (guess > max)
  347. {
  348. guess = max;
  349. f_current = -f_current; // There must be a change of sign!
  350. break;
  351. }
  352. multiplier *= e > 1024 ? 8 : 2;
  353. unpack_0(f(guess), f_current);
  354. }
  355. }
  356. else
  357. {
  358. //
  359. // If min and max are negative we have to divide to head towards max:
  360. //
  361. while (--count && ((f_current < 0) == (f0 < 0)))
  362. {
  363. min = guess;
  364. guess /= multiplier;
  365. if (guess > max)
  366. {
  367. guess = max;
  368. f_current = -f_current; // There must be a change of sign!
  369. break;
  370. }
  371. multiplier *= e > 1024 ? 8 : 2;
  372. unpack_0(f(guess), f_current);
  373. }
  374. }
  375. if (count)
  376. {
  377. max = guess;
  378. if (multiplier > 16)
  379. return (guess0 - guess) + bracket_root_towards_min(f, guess, f_current, min, max, count);
  380. }
  381. return guess0 - (max + min) / 2;
  382. }
  383. template <class F, class T>
  384. T bracket_root_towards_min(F f, T guess, const T& f0, T& min, T& max, std::uintmax_t& count) noexcept(BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  385. {
  386. using std::fabs;
  387. using std::ldexp;
  388. using std::abs;
  389. using std::frexp;
  390. if (count < 2)
  391. return guess - (max + min) / 2; // Not enough counts left to do anything!!
  392. //
  393. // Move guess towards min until we bracket the root, updating min and max as we go:
  394. //
  395. int e;
  396. frexp(guess / min, &e);
  397. e = abs(e);
  398. T guess0 = guess;
  399. T multiplier = e < 64 ? static_cast<T>(2) : static_cast<T>(ldexp(T(1), e / 32));
  400. T f_current = f0;
  401. if (fabs(min) < fabs(max))
  402. {
  403. while (--count && ((f_current < 0) == (f0 < 0)))
  404. {
  405. max = guess;
  406. guess /= multiplier;
  407. if (guess < min)
  408. {
  409. guess = min;
  410. f_current = -f_current; // There must be a change of sign!
  411. break;
  412. }
  413. multiplier *= e > 1024 ? 8 : 2;
  414. unpack_0(f(guess), f_current);
  415. }
  416. }
  417. else
  418. {
  419. //
  420. // If min and max are negative we have to multiply to head towards min:
  421. //
  422. while (--count && ((f_current < 0) == (f0 < 0)))
  423. {
  424. max = guess;
  425. guess *= multiplier;
  426. if (guess < min)
  427. {
  428. guess = min;
  429. f_current = -f_current; // There must be a change of sign!
  430. break;
  431. }
  432. multiplier *= e > 1024 ? 8 : 2;
  433. unpack_0(f(guess), f_current);
  434. }
  435. }
  436. if (count)
  437. {
  438. min = guess;
  439. if (multiplier > 16)
  440. return (guess0 - guess) + bracket_root_towards_max(f, guess, f_current, min, max, count);
  441. }
  442. return guess0 - (max + min) / 2;
  443. }
  444. template <class Stepper, class F, class T>
  445. T second_order_root_finder(F f, T guess, T min, T max, int digits, std::uintmax_t& max_iter) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  446. {
  447. BOOST_MATH_STD_USING
  448. #ifdef BOOST_MATH_INSTRUMENT
  449. std::cout << "Second order root iteration, guess = " << guess << ", min = " << min << ", max = " << max
  450. << ", digits = " << digits << ", max_iter = " << max_iter << "\n";
  451. #endif
  452. static const char* function = "boost::math::tools::halley_iterate<%1%>";
  453. if (min >= max)
  454. {
  455. return policies::raise_evaluation_error(function, "Range arguments in wrong order in boost::math::tools::halley_iterate(first arg=%1%)", min, boost::math::policies::policy<>());
  456. }
  457. T f0(0), f1, f2;
  458. T result = guess;
  459. T factor = ldexp(static_cast<T>(1.0), 1 - digits);
  460. T delta = (std::max)(T(10000000 * guess), T(10000000)); // arbitrarily large delta
  461. T last_f0 = 0;
  462. T delta1 = delta;
  463. T delta2 = delta;
  464. bool out_of_bounds_sentry = false;
  465. #ifdef BOOST_MATH_INSTRUMENT
  466. std::cout << "Second order root iteration, limit = " << factor << "\n";
  467. #endif
  468. //
  469. // We use these to sanity check that we do actually bracket a root,
  470. // we update these to the function value when we update the endpoints
  471. // of the range. Then, provided at some point we update both endpoints
  472. // checking that max_range_f * min_range_f <= 0 verifies there is a root
  473. // to be found somewhere. Note that if there is no root, and we approach
  474. // a local minima, then the derivative will go to zero, and hence the next
  475. // step will jump out of bounds (or at least past the minima), so this
  476. // check *should* happen in pathological cases.
  477. //
  478. T max_range_f = 0;
  479. T min_range_f = 0;
  480. std::uintmax_t count(max_iter);
  481. do {
  482. last_f0 = f0;
  483. delta2 = delta1;
  484. delta1 = delta;
  485. #ifndef BOOST_NO_EXCEPTIONS
  486. try
  487. #endif
  488. {
  489. detail::unpack_tuple(f(result), f0, f1, f2);
  490. }
  491. #ifndef BOOST_NO_EXCEPTIONS
  492. catch (const std::overflow_error&)
  493. {
  494. f0 = max > 0 ? tools::max_value<T>() : -tools::min_value<T>();
  495. f1 = f2 = 0;
  496. }
  497. #endif
  498. --count;
  499. BOOST_MATH_INSTRUMENT_VARIABLE(f0);
  500. BOOST_MATH_INSTRUMENT_VARIABLE(f1);
  501. BOOST_MATH_INSTRUMENT_VARIABLE(f2);
  502. if (0 == f0)
  503. break;
  504. if (f1 == 0)
  505. {
  506. // Oops zero derivative!!!
  507. detail::handle_zero_derivative(f, last_f0, f0, delta, result, guess, min, max);
  508. }
  509. else
  510. {
  511. if (f2 != 0)
  512. {
  513. delta = Stepper::step(result, f0, f1, f2);
  514. if (delta * f1 / f0 < 0)
  515. {
  516. // Oh dear, we have a problem as Newton and Halley steps
  517. // disagree about which way we should move. Probably
  518. // there is cancelation error in the calculation of the
  519. // Halley step, or else the derivatives are so small
  520. // that their values are basically trash. We will move
  521. // in the direction indicated by a Newton step, but
  522. // by no more than twice the current guess value, otherwise
  523. // we can jump way out of bounds if we're not careful.
  524. // See https://svn.boost.org/trac/boost/ticket/8314.
  525. delta = f0 / f1;
  526. if (fabs(delta) > 2 * fabs(result))
  527. delta = (delta < 0 ? -1 : 1) * 2 * fabs(result);
  528. }
  529. }
  530. else
  531. delta = f0 / f1;
  532. }
  533. #ifdef BOOST_MATH_INSTRUMENT
  534. std::cout << "Second order root iteration, delta = " << delta << ", residual = " << f0 << "\n";
  535. #endif
  536. // We need to avoid delta/delta2 overflowing here:
  537. T convergence = (fabs(delta2) > 1) || (fabs(tools::max_value<T>() * delta2) > fabs(delta)) ? fabs(delta / delta2) : tools::max_value<T>();
  538. if ((convergence > 0.8) && (convergence < 2))
  539. {
  540. // last two steps haven't converged.
  541. if (fabs(min) < 1 ? fabs(1000 * min) < fabs(max) : fabs(max / min) > 1000)
  542. {
  543. if(delta > 0)
  544. delta = bracket_root_towards_min(f, result, f0, min, max, count);
  545. else
  546. delta = bracket_root_towards_max(f, result, f0, min, max, count);
  547. }
  548. else
  549. {
  550. delta = (delta > 0) ? (result - min) / 2 : (result - max) / 2;
  551. if ((result != 0) && (fabs(delta) > result))
  552. delta = sign(delta) * fabs(result) * 0.9f; // protect against huge jumps!
  553. }
  554. // reset delta2 so that this branch will *not* be taken on the
  555. // next iteration:
  556. delta2 = delta * 3;
  557. delta1 = delta * 3;
  558. BOOST_MATH_INSTRUMENT_VARIABLE(delta);
  559. }
  560. guess = result;
  561. result -= delta;
  562. BOOST_MATH_INSTRUMENT_VARIABLE(result);
  563. // check for out of bounds step:
  564. if (result < min)
  565. {
  566. T diff = ((fabs(min) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(min)))
  567. ? T(1000)
  568. : (fabs(min) < 1) && (fabs(tools::max_value<T>() * min) < fabs(result))
  569. ? ((min < 0) != (result < 0)) ? -tools::max_value<T>() : tools::max_value<T>() : T(result / min);
  570. if (fabs(diff) < 1)
  571. diff = 1 / diff;
  572. if (!out_of_bounds_sentry && (diff > 0) && (diff < 3))
  573. {
  574. // Only a small out of bounds step, lets assume that the result
  575. // is probably approximately at min:
  576. delta = 0.99f * (guess - min);
  577. result = guess - delta;
  578. out_of_bounds_sentry = true; // only take this branch once!
  579. }
  580. else
  581. {
  582. if (fabs(float_distance(min, max)) < 2)
  583. {
  584. result = guess = (min + max) / 2;
  585. break;
  586. }
  587. delta = bracket_root_towards_min(f, guess, f0, min, max, count);
  588. result = guess - delta;
  589. if (result <= min)
  590. result = float_next(min);
  591. if (result >= max)
  592. result = float_prior(max);
  593. guess = min;
  594. continue;
  595. }
  596. }
  597. else if (result > max)
  598. {
  599. T diff = ((fabs(max) < 1) && (fabs(result) > 1) && (tools::max_value<T>() / fabs(result) < fabs(max))) ? T(1000) : T(result / max);
  600. if (fabs(diff) < 1)
  601. diff = 1 / diff;
  602. if (!out_of_bounds_sentry && (diff > 0) && (diff < 3))
  603. {
  604. // Only a small out of bounds step, lets assume that the result
  605. // is probably approximately at min:
  606. delta = 0.99f * (guess - max);
  607. result = guess - delta;
  608. out_of_bounds_sentry = true; // only take this branch once!
  609. }
  610. else
  611. {
  612. if (fabs(float_distance(min, max)) < 2)
  613. {
  614. result = guess = (min + max) / 2;
  615. break;
  616. }
  617. delta = bracket_root_towards_max(f, guess, f0, min, max, count);
  618. result = guess - delta;
  619. if (result >= max)
  620. result = float_prior(max);
  621. if (result <= min)
  622. result = float_next(min);
  623. guess = min;
  624. continue;
  625. }
  626. }
  627. // update brackets:
  628. if (delta > 0)
  629. {
  630. max = guess;
  631. max_range_f = f0;
  632. }
  633. else
  634. {
  635. min = guess;
  636. min_range_f = f0;
  637. }
  638. //
  639. // Sanity check that we bracket the root:
  640. //
  641. if (max_range_f * min_range_f > 0)
  642. {
  643. return policies::raise_evaluation_error(function, "There appears to be no root to be found in boost::math::tools::newton_raphson_iterate, perhaps we have a local minima near current best guess of %1%", guess, boost::math::policies::policy<>());
  644. }
  645. } while(count && (fabs(result * factor) < fabs(delta)));
  646. max_iter -= count;
  647. #ifdef BOOST_MATH_INSTRUMENT
  648. std::cout << "Second order root finder required " << max_iter << " iterations.\n";
  649. #endif
  650. return result;
  651. }
  652. } // T second_order_root_finder
  653. template <class F, class T>
  654. T halley_iterate(F f, T guess, T min, T max, int digits, std::uintmax_t& max_iter) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  655. {
  656. return detail::second_order_root_finder<detail::halley_step>(f, guess, min, max, digits, max_iter);
  657. }
  658. template <class F, class T>
  659. inline T halley_iterate(F f, T guess, T min, T max, int digits) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  660. {
  661. std::uintmax_t m = (std::numeric_limits<std::uintmax_t>::max)();
  662. return halley_iterate(f, guess, min, max, digits, m);
  663. }
  664. namespace detail {
  665. struct schroder_stepper
  666. {
  667. template <class T>
  668. static T step(const T& x, const T& f0, const T& f1, const T& f2) noexcept(BOOST_MATH_IS_FLOAT(T))
  669. {
  670. using std::fabs;
  671. T ratio = f0 / f1;
  672. T delta;
  673. if ((x != 0) && (fabs(ratio / x) < 0.1))
  674. {
  675. delta = ratio + (f2 / (2 * f1)) * ratio * ratio;
  676. // check second derivative doesn't over compensate:
  677. if (delta * ratio < 0)
  678. delta = ratio;
  679. }
  680. else
  681. delta = ratio; // fall back to Newton iteration.
  682. return delta;
  683. }
  684. };
  685. }
  686. template <class F, class T>
  687. T schroder_iterate(F f, T guess, T min, T max, int digits, std::uintmax_t& max_iter) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  688. {
  689. return detail::second_order_root_finder<detail::schroder_stepper>(f, guess, min, max, digits, max_iter);
  690. }
  691. template <class F, class T>
  692. inline T schroder_iterate(F f, T guess, T min, T max, int digits) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  693. {
  694. std::uintmax_t m = (std::numeric_limits<std::uintmax_t>::max)();
  695. return schroder_iterate(f, guess, min, max, digits, m);
  696. }
  697. //
  698. // These two are the old spelling of this function, retained for backwards compatibility just in case:
  699. //
  700. template <class F, class T>
  701. T schroeder_iterate(F f, T guess, T min, T max, int digits, std::uintmax_t& max_iter) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  702. {
  703. return detail::second_order_root_finder<detail::schroder_stepper>(f, guess, min, max, digits, max_iter);
  704. }
  705. template <class F, class T>
  706. inline T schroeder_iterate(F f, T guess, T min, T max, int digits) noexcept(policies::is_noexcept_error_policy<policies::policy<> >::value&& BOOST_MATH_IS_FLOAT(T) && noexcept(std::declval<F>()(std::declval<T>())))
  707. {
  708. std::uintmax_t m = (std::numeric_limits<std::uintmax_t>::max)();
  709. return schroder_iterate(f, guess, min, max, digits, m);
  710. }
  711. #ifndef BOOST_NO_CXX11_AUTO_DECLARATIONS
  712. /*
  713. * Why do we set the default maximum number of iterations to the number of digits in the type?
  714. * Because for double roots, the number of digits increases linearly with the number of iterations,
  715. * so this default should recover full precision even in this somewhat pathological case.
  716. * For isolated roots, the problem is so rapidly convergent that this doesn't matter at all.
  717. */
  718. template<class Complex, class F>
  719. Complex complex_newton(F g, Complex guess, int max_iterations = std::numeric_limits<typename Complex::value_type>::digits)
  720. {
  721. typedef typename Complex::value_type Real;
  722. using std::norm;
  723. using std::abs;
  724. using std::max;
  725. // z0, z1, and z2 cannot be the same, in case we immediately need to resort to Muller's Method:
  726. Complex z0 = guess + Complex(1, 0);
  727. Complex z1 = guess + Complex(0, 1);
  728. Complex z2 = guess;
  729. do {
  730. auto pair = g(z2);
  731. if (norm(pair.second) == 0)
  732. {
  733. // Muller's method. Notation follows Numerical Recipes, 9.5.2:
  734. Complex q = (z2 - z1) / (z1 - z0);
  735. auto P0 = g(z0);
  736. auto P1 = g(z1);
  737. Complex qp1 = static_cast<Complex>(1) + q;
  738. Complex A = q * (pair.first - qp1 * P1.first + q * P0.first);
  739. Complex B = (static_cast<Complex>(2) * q + static_cast<Complex>(1)) * pair.first - qp1 * qp1 * P1.first + q * q * P0.first;
  740. Complex C = qp1 * pair.first;
  741. Complex rad = sqrt(B * B - static_cast<Complex>(4) * A * C);
  742. Complex denom1 = B + rad;
  743. Complex denom2 = B - rad;
  744. Complex correction = (z1 - z2) * static_cast<Complex>(2) * C;
  745. if (norm(denom1) > norm(denom2))
  746. {
  747. correction /= denom1;
  748. }
  749. else
  750. {
  751. correction /= denom2;
  752. }
  753. z0 = z1;
  754. z1 = z2;
  755. z2 = z2 + correction;
  756. }
  757. else
  758. {
  759. z0 = z1;
  760. z1 = z2;
  761. z2 = z2 - (pair.first / pair.second);
  762. }
  763. // See: https://math.stackexchange.com/questions/3017766/constructing-newton-iteration-converging-to-non-root
  764. // If f' is continuous, then convergence of x_n -> x* implies f(x*) = 0.
  765. // This condition approximates this convergence condition by requiring three consecutive iterates to be clustered.
  766. Real tol = (max)(abs(z2) * std::numeric_limits<Real>::epsilon(), std::numeric_limits<Real>::epsilon());
  767. bool real_close = abs(z0.real() - z1.real()) < tol && abs(z0.real() - z2.real()) < tol && abs(z1.real() - z2.real()) < tol;
  768. bool imag_close = abs(z0.imag() - z1.imag()) < tol && abs(z0.imag() - z2.imag()) < tol && abs(z1.imag() - z2.imag()) < tol;
  769. if (real_close && imag_close)
  770. {
  771. return z2;
  772. }
  773. } while (max_iterations--);
  774. // The idea is that if we can get abs(f) < eps, we should, but if we go through all these iterations
  775. // and abs(f) < sqrt(eps), then roundoff error simply does not allow that we can evaluate f to < eps
  776. // This is somewhat awkward as it isn't scale invariant, but using the Daubechies coefficient example code,
  777. // I found this condition generates correct roots, whereas the scale invariant condition discussed here:
  778. // https://scicomp.stackexchange.com/questions/30597/defining-a-condition-number-and-termination-criteria-for-newtons-method
  779. // allows nonroots to be passed off as roots.
  780. auto pair = g(z2);
  781. if (abs(pair.first) < sqrt(std::numeric_limits<Real>::epsilon()))
  782. {
  783. return z2;
  784. }
  785. return { std::numeric_limits<Real>::quiet_NaN(),
  786. std::numeric_limits<Real>::quiet_NaN() };
  787. }
  788. #endif
  789. #if !defined(BOOST_NO_CXX17_IF_CONSTEXPR)
  790. // https://stackoverflow.com/questions/48979861/numerically-stable-method-for-solving-quadratic-equations/50065711
  791. namespace detail
  792. {
  793. #if defined(BOOST_GNU_STDLIB) && !defined(_GLIBCXX_USE_C99_MATH_TR1)
  794. inline float fma_workaround(float x, float y, float z) { return ::fmaf(x, y, z); }
  795. inline double fma_workaround(double x, double y, double z) { return ::fma(x, y, z); }
  796. #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
  797. inline long double fma_workaround(long double x, long double y, long double z) { return ::fmal(x, y, z); }
  798. #endif
  799. #endif
  800. template<class T>
  801. inline T discriminant(T const& a, T const& b, T const& c)
  802. {
  803. T w = 4 * a * c;
  804. #if defined(BOOST_GNU_STDLIB) && !defined(_GLIBCXX_USE_C99_MATH_TR1)
  805. T e = fma_workaround(-c, 4 * a, w);
  806. T f = fma_workaround(b, b, -w);
  807. #else
  808. T e = std::fma(-c, 4 * a, w);
  809. T f = std::fma(b, b, -w);
  810. #endif
  811. return f + e;
  812. }
  813. template<class T>
  814. std::pair<T, T> quadratic_roots_imp(T const& a, T const& b, T const& c)
  815. {
  816. #if defined(BOOST_GNU_STDLIB) && !defined(_GLIBCXX_USE_C99_MATH_TR1)
  817. using boost::math::copysign;
  818. #else
  819. using std::copysign;
  820. #endif
  821. using std::sqrt;
  822. if constexpr (std::is_floating_point<T>::value)
  823. {
  824. T nan = std::numeric_limits<T>::quiet_NaN();
  825. if (a == 0)
  826. {
  827. if (b == 0 && c != 0)
  828. {
  829. return std::pair<T, T>(nan, nan);
  830. }
  831. else if (b == 0 && c == 0)
  832. {
  833. return std::pair<T, T>(0, 0);
  834. }
  835. return std::pair<T, T>(-c / b, -c / b);
  836. }
  837. if (b == 0)
  838. {
  839. T x0_sq = -c / a;
  840. if (x0_sq < 0) {
  841. return std::pair<T, T>(nan, nan);
  842. }
  843. T x0 = sqrt(x0_sq);
  844. return std::pair<T, T>(-x0, x0);
  845. }
  846. T discriminant = detail::discriminant(a, b, c);
  847. // Is there a sane way to flush very small negative values to zero?
  848. // If there is I don't know of it.
  849. if (discriminant < 0)
  850. {
  851. return std::pair<T, T>(nan, nan);
  852. }
  853. T q = -(b + copysign(sqrt(discriminant), b)) / T(2);
  854. T x0 = q / a;
  855. T x1 = c / q;
  856. if (x0 < x1)
  857. {
  858. return std::pair<T, T>(x0, x1);
  859. }
  860. return std::pair<T, T>(x1, x0);
  861. }
  862. else if constexpr (boost::math::tools::is_complex_type<T>::value)
  863. {
  864. typename T::value_type nan = std::numeric_limits<typename T::value_type>::quiet_NaN();
  865. if (a.real() == 0 && a.imag() == 0)
  866. {
  867. using std::norm;
  868. if (b.real() == 0 && b.imag() && norm(c) != 0)
  869. {
  870. return std::pair<T, T>({ nan, nan }, { nan, nan });
  871. }
  872. else if (b.real() == 0 && b.imag() && c.real() == 0 && c.imag() == 0)
  873. {
  874. return std::pair<T, T>({ 0,0 }, { 0,0 });
  875. }
  876. return std::pair<T, T>(-c / b, -c / b);
  877. }
  878. if (b.real() == 0 && b.imag() == 0)
  879. {
  880. T x0_sq = -c / a;
  881. T x0 = sqrt(x0_sq);
  882. return std::pair<T, T>(-x0, x0);
  883. }
  884. // There's no fma for complex types:
  885. T discriminant = b * b - T(4) * a * c;
  886. T q = -(b + sqrt(discriminant)) / T(2);
  887. return std::pair<T, T>(q / a, c / q);
  888. }
  889. else // Most likely the type is a boost.multiprecision.
  890. { //There is no fma for multiprecision, and in addition it doesn't seem to be useful, so revert to the naive computation.
  891. T nan = std::numeric_limits<T>::quiet_NaN();
  892. if (a == 0)
  893. {
  894. if (b == 0 && c != 0)
  895. {
  896. return std::pair<T, T>(nan, nan);
  897. }
  898. else if (b == 0 && c == 0)
  899. {
  900. return std::pair<T, T>(0, 0);
  901. }
  902. return std::pair<T, T>(-c / b, -c / b);
  903. }
  904. if (b == 0)
  905. {
  906. T x0_sq = -c / a;
  907. if (x0_sq < 0) {
  908. return std::pair<T, T>(nan, nan);
  909. }
  910. T x0 = sqrt(x0_sq);
  911. return std::pair<T, T>(-x0, x0);
  912. }
  913. T discriminant = b * b - 4 * a * c;
  914. if (discriminant < 0)
  915. {
  916. return std::pair<T, T>(nan, nan);
  917. }
  918. T q = -(b + copysign(sqrt(discriminant), b)) / T(2);
  919. T x0 = q / a;
  920. T x1 = c / q;
  921. if (x0 < x1)
  922. {
  923. return std::pair<T, T>(x0, x1);
  924. }
  925. return std::pair<T, T>(x1, x0);
  926. }
  927. }
  928. } // namespace detail
  929. template<class T1, class T2 = T1, class T3 = T1>
  930. inline std::pair<typename tools::promote_args<T1, T2, T3>::type, typename tools::promote_args<T1, T2, T3>::type> quadratic_roots(T1 const& a, T2 const& b, T3 const& c)
  931. {
  932. typedef typename tools::promote_args<T1, T2, T3>::type value_type;
  933. return detail::quadratic_roots_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(c));
  934. }
  935. #endif
  936. } // namespace tools
  937. } // namespace math
  938. } // namespace boost
  939. #endif // BOOST_MATH_TOOLS_NEWTON_SOLVER_HPP