root_finding_fifth.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. // root_finding_fith.cpp
  2. // Copyright Paul A. Bristow 2014.
  3. // Use, modification and distribution are subject to the
  4. // Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt
  6. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. // Example of finding fifth root using Newton-Raphson, Halley, Schroder, TOMS748 .
  8. // Note that this file contains Quickbook mark-up as well as code
  9. // and comments, don't change any of the special comment mark-ups!
  10. // To get (copious!) diagnostic output, add make this define here or elsewhere.
  11. //#define BOOST_MATH_INSTRUMENT
  12. //[root_fifth_headers
  13. /*
  14. This example demonstrates how to use the Boost.Math tools for root finding,
  15. taking the fifth root function (fifth_root) as an example.
  16. It shows how use of derivatives can improve the speed.
  17. First some includes that will be needed.
  18. Using statements are provided to list what functions are being used in this example:
  19. you can of course qualify the names in other ways.
  20. */
  21. #include <boost/math/tools/roots.hpp>
  22. using boost::math::policies::policy;
  23. using boost::math::tools::newton_raphson_iterate;
  24. using boost::math::tools::halley_iterate;
  25. using boost::math::tools::eps_tolerance; // Binary functor for specified number of bits.
  26. using boost::math::tools::bracket_and_solve_root;
  27. using boost::math::tools::toms748_solve;
  28. #include <boost/math/special_functions/next.hpp>
  29. #include <tuple>
  30. #include <utility> // pair, make_pair
  31. //] [/root_finding_headers]
  32. #include <iostream>
  33. using std::cout; using std::endl;
  34. #include <iomanip>
  35. using std::setw; using std::setprecision;
  36. #include <limits>
  37. using std::numeric_limits;
  38. /*
  39. //[root_finding_fifth_1
  40. Let's suppose we want to find the fifth root of a number.
  41. The equation we want to solve is:
  42. __spaces ['f](x) = x[fifth]
  43. We will first solve this without using any information
  44. about the slope or curvature of the fifth function.
  45. If your differentiation is a little rusty
  46. (or you are faced with an equation whose complexity is daunting,
  47. then you can get help, for example from the invaluable
  48. http://www.wolframalpha.com/ site
  49. entering the commmand
  50. differentiate x^5
  51. or the Wolfram Language command
  52. D[x^5, x]
  53. gives the output
  54. d/dx(x^5) = 5 x^4
  55. and to get the second differential, enter
  56. second differentiate x^5
  57. or the Wolfram Language
  58. D[x^5, {x, 2}]
  59. to get the output
  60. d^2/dx^2(x^5) = 20 x^3
  61. or
  62. 20 x^3
  63. To get a reference value we can enter
  64. fifth root 3126
  65. or
  66. N[3126^(1/5), 50]
  67. to get a result with a precision of 50 decimal digits
  68. 5.0003199590478625588206333405631053401128722314376
  69. (We could also get a reference value using Boost.Multiprecision).
  70. We then show how adding what we can know, for this function, about the slope,
  71. the 1st derivation /f'(x)/, will speed homing in on the solution,
  72. and then finally how adding the curvature /f''(x)/ as well will improve even more.
  73. The 1st and 2nd derivatives of x[fifth] are:
  74. __spaces ['f]\'(x) = 2x[sup2]
  75. __spaces ['f]\'\'(x) = 6x
  76. */
  77. //] [/root_finding_fifth_1]
  78. //[root_finding_fifth_functor_noderiv
  79. template <class T>
  80. struct fifth_functor_noderiv
  81. { // fifth root of x using only function - no derivatives.
  82. fifth_functor_noderiv(T const& to_find_root_of) : value(to_find_root_of)
  83. { // Constructor stores value to find root of.
  84. // For example: calling fifth_functor<T>(x) to get fifth root of x.
  85. }
  86. T operator()(T const& x)
  87. { //! \returns f(x) - value.
  88. T fx = x*x*x*x*x - value; // Difference (estimate x^5 - value).
  89. return fx;
  90. }
  91. private:
  92. T value; // to be 'fifth_rooted'.
  93. };
  94. //] [/root_finding_fifth_functor_noderiv]
  95. //cout << ", std::numeric_limits<" << typeid(T).name() << ">::digits = " << digits
  96. // << ", accuracy " << get_digits << " bits."<< endl;
  97. /*`Implementing the fifth root function itself is fairly trivial now:
  98. the hardest part is finding a good approximation to begin with.
  99. In this case we'll just divide the exponent by five.
  100. (There are better but more complex guess algorithms used in 'real-life'.)
  101. fifth root function is 'Really Well Behaved' in that it is monotonic
  102. and has only one root
  103. (we leave negative values 'as an exercise for the student').
  104. */
  105. //[root_finding_fifth_noderiv
  106. template <class T>
  107. T fifth_noderiv(T x)
  108. { //! \returns fifth root of x using bracket_and_solve (no derivatives).
  109. using namespace std; // Help ADL of std functions.
  110. using namespace boost::math::tools; // For bracket_and_solve_root.
  111. int exponent;
  112. frexp(x, &exponent); // Get exponent of z (ignore mantissa).
  113. T guess = ldexp(1., exponent / 5); // Rough guess is to divide the exponent by five.
  114. T factor = 2; // To multiply and divide guess to bracket.
  115. // digits used to control how accurate to try to make the result.
  116. // int digits = 3 * std::numeric_limits<T>::digits / 4; // 3/4 maximum possible binary digits accuracy for type T.
  117. int digits = std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy for type T.
  118. //boost::uintmax_t maxit = (std::numeric_limits<boost::uintmax_t>::max)();
  119. // (std::numeric_limits<boost::uintmax_t>::max)() = 18446744073709551615
  120. // which is more than anyone might wish to wait for!!!
  121. // so better to choose some reasonable estimate of how many iterations may be needed.
  122. const boost::uintmax_t maxit = 50; // Chosen max iterations,
  123. // but updated on exit with actual iteration count.
  124. // We could also have used a maximum iterations provided by any policy:
  125. // boost::uintmax_t max_it = policies::get_max_root_iterations<Policy>();
  126. boost::uintmax_t it = maxit; // Initally our chosen max iterations,
  127. bool is_rising = true; // So if result if guess^5 is too low, try increasing guess.
  128. eps_tolerance<double> tol(digits);
  129. std::pair<T, T> r =
  130. bracket_and_solve_root(fifth_functor_noderiv<T>(x), guess, factor, is_rising, tol, it);
  131. // because the iteration count is updating,
  132. // you can't call with a literal maximum iterations value thus:
  133. //bracket_and_solve_root(fifth_functor_noderiv<T>(x), guess, factor, is_rising, tol, 20);
  134. // Can show how many iterations (this information is lost outside fifth_noderiv).
  135. cout << "Iterations " << it << endl;
  136. if (it >= maxit)
  137. { // Failed to converge (or is jumping between bracket values).
  138. cout << "Unable to locate solution in chosen iterations:"
  139. " Current best guess is between " << r.first << " and " << r.second << endl;
  140. }
  141. T distance = float_distance(r.first, r.second);
  142. if (distance > 0)
  143. { //
  144. std::cout << distance << " bits separate the bracketing values." << std::endl;
  145. for (int i = 0; i < distance; i++)
  146. { // Show all the values within the bracketing values.
  147. std::cout << float_advance(r.first, i) << std::endl;
  148. }
  149. }
  150. else
  151. { // distance == 0 and r.second == r.first
  152. std::cout << "Converged to a single value " << r.first << std::endl;
  153. }
  154. return r.first + (r.second - r.first) / 2; // return midway between bracketed interval.
  155. } // T fifth_noderiv(T x)
  156. //] [/root_finding_fifth_noderiv]
  157. // maxit = 10
  158. // Unable to locate solution in chosen iterations: Current best guess is between 3.0365889718756613 and 3.0365889718756627
  159. /*`
  160. We now solve the same problem, but using more information about the function,
  161. to show how this can speed up finding the best estimate of the root.
  162. For this function, the 1st differential (the slope of the tangent to a curve at any point) is known.
  163. [@http://en.wikipedia.org/wiki/Derivative#Derivatives_of_elementary_functions Derivatives]
  164. gives some reminders.
  165. Using the rule that the derivative of x^n for positive n (actually all nonzero n) is nx^n-1,
  166. allows use to get the 1st differential as 3x^2.
  167. To see how this extra information is used to find the root, view this demo:
  168. [@http://en.wikipedia.org/wiki/Newton%27s_methodNewton Newton-Raphson iterations].
  169. We need to define a different functor that returns
  170. both the evaluation of the function to solve, along with its first derivative:
  171. To \'return\' two values, we use a pair of floating-point values:
  172. */
  173. //[root_finding_fifth_functor_1stderiv
  174. template <class T>
  175. struct fifth_functor_1stderiv
  176. { // Functor returning function and 1st derivative.
  177. fifth_functor_1stderiv(T const& target) : value(target)
  178. { // Constructor stores the value to be 'fifth_rooted'.
  179. }
  180. std::pair<T, T> operator()(T const& z) // z is best estimate so far.
  181. { // Return both f(x) and first derivative f'(x).
  182. T fx = z*z*z*z*z - value; // Difference estimate fx = x^5 - value.
  183. T d1x = 5 * z*z*z*z; // 1st derivative d1x = 5x^4.
  184. return std::make_pair(fx, d1x); // 'return' both fx and d1x.
  185. }
  186. private:
  187. T value; // to be 'fifth_rooted'.
  188. }; // fifth_functor_1stderiv
  189. //] [/root_finding_fifth_functor_1stderiv]
  190. /*`Our fifth root function using fifth_functor_1stderiv is now:*/
  191. //[root_finding_fifth_1deriv
  192. template <class T>
  193. T fifth_1deriv(T x)
  194. { //! \return fifth root of x using 1st derivative and Newton_Raphson.
  195. using namespace std; // For frexp, ldexp, numeric_limits.
  196. using namespace boost::math::tools; // For newton_raphson_iterate.
  197. int exponent;
  198. frexp(x, &exponent); // Get exponent of x (ignore mantissa).
  199. T guess = ldexp(1., exponent / 5); // Rough guess is to divide the exponent by three.
  200. // Set an initial bracket interval.
  201. T min = ldexp(0.5, exponent / 5); // Minimum possible value is half our guess.
  202. T max = ldexp(2., exponent / 5);// Maximum possible value is twice our guess.
  203. // digits used to control how accurate to try to make the result.
  204. int digits = std::numeric_limits<T>::digits; // Maximum possible binary digits accuracy for type T.
  205. const boost::uintmax_t maxit = 20; // Optionally limit the number of iterations.
  206. boost::uintmax_t it = maxit; // limit the number of iterations.
  207. //cout << "Max Iterations " << maxit << endl; //
  208. T result = newton_raphson_iterate(fifth_functor_1stderiv<T>(x), guess, min, max, digits, it);
  209. // Can check and show how many iterations (updated by newton_raphson_iterate).
  210. cout << it << " iterations (from max of " << maxit << ")" << endl;
  211. return result;
  212. } // fifth_1deriv
  213. //] [/root_finding_fifth_1deriv]
  214. // int get_digits = (digits * 2) /3; // Two thirds of maximum possible accuracy.
  215. //boost::uintmax_t maxit = (std::numeric_limits<boost::uintmax_t>::max)();
  216. // the default (std::numeric_limits<boost::uintmax_t>::max)() = 18446744073709551615
  217. // which is more than we might wish to wait for!!! so we can reduce it
  218. /*`
  219. Finally need to define yet another functor that returns
  220. both the evaluation of the function to solve,
  221. along with its first and second derivatives:
  222. f''(x) = 3 * 3x
  223. To \'return\' three values, we use a tuple of three floating-point values:
  224. */
  225. //[root_finding_fifth_functor_2deriv
  226. template <class T>
  227. struct fifth_functor_2deriv
  228. { // Functor returning both 1st and 2nd derivatives.
  229. fifth_functor_2deriv(T const& to_find_root_of) : value(to_find_root_of)
  230. { // Constructor stores value to find root of, for example:
  231. }
  232. // using boost::math::tuple; // to return three values.
  233. std::tuple<T, T, T> operator()(T const& x)
  234. { // Return both f(x) and f'(x) and f''(x).
  235. T fx = x*x*x*x*x - value; // Difference (estimate x^3 - value).
  236. T dx = 5 * x*x*x*x; // 1st derivative = 5x^4.
  237. T d2x = 20 * x*x*x; // 2nd derivative = 20 x^3
  238. return std::make_tuple(fx, dx, d2x); // 'return' fx, dx and d2x.
  239. }
  240. private:
  241. T value; // to be 'fifth_rooted'.
  242. }; // struct fifth_functor_2deriv
  243. //] [/root_finding_fifth_functor_2deriv]
  244. /*`Our fifth function is now:*/
  245. //[root_finding_fifth_2deriv
  246. template <class T>
  247. T fifth_2deriv(T x)
  248. { // return fifth root of x using 1st and 2nd derivatives and Halley.
  249. using namespace std; // Help ADL of std functions.
  250. using namespace boost::math; // halley_iterate
  251. int exponent;
  252. frexp(x, &exponent); // Get exponent of z (ignore mantissa).
  253. T guess = ldexp(1., exponent / 5); // Rough guess is to divide the exponent by three.
  254. T min = ldexp(0.5, exponent / 5); // Minimum possible value is half our guess.
  255. T max = ldexp(2., exponent / 5); // Maximum possible value is twice our guess.
  256. int digits = std::numeric_limits<T>::digits / 2; // Half maximum possible binary digits accuracy for type T.
  257. const boost::uintmax_t maxit = 50;
  258. boost::uintmax_t it = maxit;
  259. T result = halley_iterate(fifth_functor_2deriv<T>(x), guess, min, max, digits, it);
  260. // Can show how many iterations (updated by halley_iterate).
  261. cout << it << " iterations (from max of " << maxit << ")" << endl;
  262. return result;
  263. } // fifth_2deriv(x)
  264. //] [/root_finding_fifth_2deriv]
  265. int main()
  266. {
  267. //[root_finding_example_1
  268. cout << "fifth Root finding (fifth) Example." << endl;
  269. // Show all possibly significant decimal digits.
  270. cout.precision(std::numeric_limits<double>::max_digits10);
  271. // or use cout.precision(max_digits10 = 2 + std::numeric_limits<double>::digits * 3010/10000);
  272. try
  273. { // Always use try'n'catch blocks with Boost.Math to get any error messages.
  274. double v27 = 3125; // Example of a value that has an exact integer fifth root.
  275. // exact value of fifth root is exactly 5.
  276. std::cout << "Fifth root of " << v27 << " is " << 5 << std::endl;
  277. double v28 = v27+1; // Example of a value whose fifth root is *not* exactly representable.
  278. // Value of fifth root is 5.0003199590478625588206333405631053401128722314376 (50 decimal digits precision)
  279. // and to std::numeric_limits<double>::max_digits10 double precision (usually 17) is
  280. double root5v2 = static_cast<double>(5.0003199590478625588206333405631053401128722314376);
  281. std::cout << "Fifth root of " << v28 << " is " << root5v2 << std::endl;
  282. // Using bracketing:
  283. double r = fifth_noderiv(v27);
  284. cout << "fifth_noderiv(" << v27 << ") = " << r << endl;
  285. r = fifth_noderiv(v28);
  286. cout << "fifth_noderiv(" << v28 << ") = " << r << endl;
  287. // Using 1st differential Newton-Raphson:
  288. r = fifth_1deriv(v27);
  289. cout << "fifth_1deriv(" << v27 << ") = " << r << endl;
  290. r = fifth_1deriv(v28);
  291. cout << "fifth_1deriv(" << v28 << ") = " << r << endl;
  292. // Using Halley with 1st and 2nd differentials.
  293. r = fifth_2deriv(v27);
  294. cout << "fifth_2deriv(" << v27 << ") = " << r << endl;
  295. r = fifth_2deriv(v28);
  296. cout << "fifth_2deriv(" << v28 << ") = " << r << endl;
  297. }
  298. catch (const std::exception& e)
  299. { // Always useful to include try & catch blocks because default policies
  300. // are to throw exceptions on arguments that cause errors like underflow, overflow.
  301. // Lacking try & catch blocks, the program will abort without a message below,
  302. // which may give some helpful clues as to the cause of the exception.
  303. std::cout <<
  304. "\n""Message from thrown exception was:\n " << e.what() << std::endl;
  305. }
  306. //] [/root_finding_example_1
  307. return 0;
  308. } // int main()
  309. //[root_finding_example_output
  310. /*`
  311. Normal output is:
  312. [pre
  313. 1> Description: Autorun "J:\Cpp\MathToolkit\test\Math_test\Release\root_finding_fifth.exe"
  314. 1> fifth Root finding (fifth) Example.
  315. 1> Fifth root of 3125 is 5
  316. 1> Fifth root of 3126 is 5.0003199590478626
  317. 1> Iterations 10
  318. 1> Converged to a single value 5
  319. 1> fifth_noderiv(3125) = 5
  320. 1> Iterations 11
  321. 1> 2 bits separate the bracketing values.
  322. 1> 5.0003199590478609
  323. 1> 5.0003199590478618
  324. 1> fifth_noderiv(3126) = 5.0003199590478618
  325. 1> 6 iterations (from max of 20)
  326. 1> fifth_1deriv(3125) = 5
  327. 1> 7 iterations (from max of 20)
  328. 1> fifth_1deriv(3126) = 5.0003199590478626
  329. 1> 4 iterations (from max of 50)
  330. 1> fifth_2deriv(3125) = 5
  331. 1> 4 iterations (from max of 50)
  332. 1> fifth_2deriv(3126) = 5.0003199590478626
  333. [/pre]
  334. to get some (much!) diagnostic output we can add
  335. #define BOOST_MATH_INSTRUMENT
  336. [pre
  337. 1> fifth Root finding (fifth) Example.
  338. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:537 a = 4 b = 8 fa = -2101 fb = 29643 count = 18
  339. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:340 a = 4.264742943548387 b = 8
  340. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:352 a = 4.264742943548387 b = 5.1409225585147951
  341. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:259 a = 4.264742943548387 b = 5.1409225585147951 d = 8 e = 4 fa = -1714.2037505671719 fb = 465.91652114644285 fd = 29643 fe = -2101
  342. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:267 q11 = -3.735257056451613 q21 = -0.045655399937094755 q31 = 0.68893005658139972 d21 = -2.9047328414222999 d31 = -0.18724955838500826
  343. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:275 q22 = -0.15074699539567221 q32 = 0.007740525571111408 d32 = -0.13385363287680208 q33 = 0.074868009790687237 c = 5.0362815354915851
  344. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:388 a = 4.264742943548387 b = 5.0362815354915851
  345. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:259 a = 4.264742943548387 b = 5.0362815354915851 d = 5.1409225585147951 e = 8 fa = -1714.2037505671719 fb = 115.03721886368339 fd = 465.91652114644285 fe = 29643
  346. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:267 q11 = -0.045655399937094755 q21 = -0.034306988726112195 q31 = 0.7230181097615842 d21 = -0.1389480117493222 d31 = -0.048520482181613811
  347. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:275 q22 = -0.00036345624935100459 q32 = 0.011175908093791367 d32 = -0.0030375853617102483 q33 = 0.00014618657296010219 c = 4.999083147976723
  348. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:408 a = 4.999083147976723 b = 5.0362815354915851
  349. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:433 a = 4.999083147976723 b = 5.0008904277935091
  350. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:434 tol = -0.00036152225583956088
  351. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:259 a = 4.999083147976723 b = 5.0008904277935091 d = 5.0362815354915851 e = 4.264742943548387 fa = -2.8641119933622576 fb = 2.7835781082976609 fd = 115.03721886368339 fe = -1714.2037505671719
  352. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:267 q11 = -0.048520482181613811 q21 = -0.00087760104664616457 q31 = 0.00091652546535745522 d21 = -0.036268708744722128 d31 = -0.00089075435142862297
  353. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:275 q22 = -1.9862562616034592e-005 q32 = 3.1952597740788757e-007 d32 = -1.2833778805050512e-005 q33 = 1.1763429980834706e-008 c = 5.0000000047314881
  354. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:388 a = 4.999083147976723 b = 5.0000000047314881
  355. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:259 a = 4.999083147976723 b = 5.0000000047314881 d = 5.0008904277935091 e = 5.0362815354915851 fa = -2.8641119933622576 fb = 1.4785900475544622e-005 fd = 2.7835781082976609 fe = 115.03721886368339
  356. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:267 q11 = -0.00087760104664616457 q21 = -4.7298032238887272e-009 q31 = 0.00091685202154135855 d21 = -0.00089042779182425238 d31 = -4.7332236912279757e-009
  357. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:275 q22 = -1.6486403607318402e-012 q32 = 1.7346209428817704e-012 d32 = -1.6858463963666777e-012 q33 = 9.0382569995250912e-016 c = 5
  358. 1> I:\modular-boost\boost/math/tools/toms748_solve.hpp:592 max_iter = 10 count = 7
  359. 1> Iterations 20
  360. 1> 0 bits separate brackets.
  361. 1> fifth_noderiv(3125) = 5
  362. ]
  363. */
  364. //] [/root_finding_example_output]