mpfr_precision.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. ///////////////////////////////////////////////////////////////
  2. // Copyright 2018 John Maddock. Distributed under the Boost
  3. // Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
  5. //[mpfr_variable
  6. /*`
  7. This example illustrates the use of variable-precision arithmetic with
  8. the `mpfr_float` number type. We'll calculate the median of the
  9. beta distribution to an absurdly high precision and compare the
  10. accuracy and times taken for various methods. That is, we want
  11. to calculate the value of `x` for which ['I[sub x](a, b) = 0.5].
  12. Ultimately we'll use Newtons method and set the precision of
  13. mpfr_float to have just enough digits at each iteration.
  14. The full source of the this program is in [@../../example/mpfr_precision.cpp]
  15. We'll skip over the #includes and using declations, and go straight to
  16. some support code, first off a simple stopwatch for performance measurement:
  17. */
  18. //=template <class clock_type>
  19. //=struct stopwatch { /*details \*/ };
  20. /*`
  21. We'll use `stopwatch<std::chono::high_resolution_clock>` as our performance measuring device.
  22. We also have a small utility class for controlling the current precision of mpfr_float:
  23. struct scoped_precision
  24. {
  25. unsigned p;
  26. scoped_precision(unsigned new_p) : p(mpfr_float::default_precision())
  27. {
  28. mpfr_float::default_precision(new_p);
  29. }
  30. ~scoped_precision()
  31. {
  32. mpfr_float::default_precision(p);
  33. }
  34. };
  35. */
  36. //<-
  37. #include <boost/multiprecision/mpfr.hpp>
  38. #include <boost/math/special_functions/beta.hpp>
  39. #include <boost/math/special_functions/relative_difference.hpp>
  40. #include <iostream>
  41. #include <chrono>
  42. using boost::multiprecision::mpfr_float;
  43. using boost::math::ibeta_inv;
  44. using namespace boost::math::policies;
  45. template <class clock_type>
  46. struct stopwatch
  47. {
  48. public:
  49. typedef typename clock_type::duration duration_type;
  50. stopwatch() : m_start(clock_type::now()) { }
  51. stopwatch(const stopwatch& other) : m_start(other.m_start) { }
  52. stopwatch& operator=(const stopwatch& other)
  53. {
  54. m_start = other.m_start;
  55. return *this;
  56. }
  57. ~stopwatch() { }
  58. float elapsed() const
  59. {
  60. return float(std::chrono::nanoseconds((clock_type::now() - m_start)).count()) / 1e9f;
  61. }
  62. void reset()
  63. {
  64. m_start = clock_type::now();
  65. }
  66. private:
  67. typename clock_type::time_point m_start;
  68. };
  69. struct scoped_precision
  70. {
  71. unsigned p;
  72. scoped_precision(unsigned new_p) : p(mpfr_float::default_precision())
  73. {
  74. mpfr_float::default_precision(new_p);
  75. }
  76. ~scoped_precision()
  77. {
  78. mpfr_float::default_precision(p);
  79. }
  80. };
  81. //->
  82. /*`
  83. We'll begin with a reference method that simply calls the Boost.Math function `ibeta_inv` and uses the
  84. full working precision of the arguments throughout. Our reference function takes 3 arguments:
  85. * The 2 parameters `a` and `b` of the beta distribution, and
  86. * The number of decimal digits precision to achieve in the result.
  87. We begin by setting the default working precision to that requested, and then, since we don't know where
  88. our arguments `a` and `b` have been or what precision they have, we make a copy of them - note that since
  89. copying also copies the precision as well as the value, we have to set the precision expicitly with a
  90. second argument to the copy. Then we can simply return the result of `ibeta_inv`:
  91. */
  92. mpfr_float beta_distribution_median_method_1(mpfr_float const& a_, mpfr_float const& b_, unsigned digits10)
  93. {
  94. scoped_precision sp(digits10);
  95. mpfr_float half(0.5), a(a_, digits10), b(b_, digits10);
  96. return ibeta_inv(a, b, half);
  97. }
  98. /*`
  99. You be wondering why we needed to change the precision of our variables `a` and `b` as well as setting the default -
  100. there are in fact two ways in which this can go wrong if we don't do that:
  101. * The variables have too much precision - this will cause all arithmetic operations involving those types to be
  102. promoted to the higher precision wasting precious calculation time.
  103. * The variables have too little precision - this will cause expressions involving only those variables to be
  104. calculated at the lower precision - for example if we calculate `exp(a)` internally, this will be evaluated at
  105. the precision of `a`, and not the current default.
  106. Since our reference method carries out all calculations at the full precision requested, an obvious refinement
  107. would be to calculate a first approximation to `double` precision and then to use Newton steps to refine it further.
  108. Our function begins the same as before: set the new default precision and then make copies of our arguments
  109. at the correct precision. We then call `ibeta_inv` with all double precision arguments, promote the result
  110. to an `mpfr_float` and perform Newton steps to obtain the result. Note that our termination condition is somewhat
  111. cude: we simply assume that we have approximately 14 digits correct from the double-precision approximation and
  112. that the precision doubles with each step. We also cheat, and use an internal Boost.Math function that calculates
  113. ['I[sub x](a, b)] and it's derivative in one go:
  114. */
  115. mpfr_float beta_distribution_median_method_2(mpfr_float const& a_, mpfr_float const& b_, unsigned digits10)
  116. {
  117. scoped_precision sp(digits10);
  118. mpfr_float half(0.5), a(a_, digits10), b(b_, digits10);
  119. mpfr_float guess = ibeta_inv((double)a, (double)b, 0.5);
  120. unsigned current_digits = 14;
  121. mpfr_float f, f1;
  122. while (current_digits < digits10)
  123. {
  124. f = boost::math::detail::ibeta_imp(a, b, guess, boost::math::policies::policy<>(), false, true, &f1) - half;
  125. guess -= f / f1;
  126. current_digits *= 2;
  127. }
  128. return guess;
  129. }
  130. /*`
  131. Before we refine the method further, it might be wise to take stock and see how method's 1 and 2 compare.
  132. We'll ask them both for 1500 digit precision, and compare against the value produced by `ibeta_inv` at 1700 digits.
  133. Here's what the results look like:
  134. [pre
  135. Method 1 time = 0.611647
  136. Relative error: 2.99991e-1501
  137. Method 2 time = 0.646746
  138. Relative error: 7.55843e-1501
  139. ]
  140. Clearly they are both equally accurate, but Method 1 is actually faster and our plan for improved performance
  141. hasn't actually worked. It turns out that we're not actually comparing like with like, because `ibeta_inv` uses
  142. Halley iteration internally which churns out more digits of precision rather more rapidly than Newton iteration.
  143. So the time we save by refining an initial `double` approximation, then loose it again by taking more iterations
  144. to get to the result.
  145. Time for a more refined approach. It follows the same form as Method 2, but now we set the working precision
  146. within the Newton iteration loop, to just enough digits to cover the expected precision at each step. That means
  147. we also create new copies of our arguments at the correct precision within the loop, and likewise change the precision
  148. of the current `guess` each time through:
  149. */
  150. mpfr_float beta_distribution_median_method_3(mpfr_float const& a_, mpfr_float const& b_, unsigned digits10)
  151. {
  152. mpfr_float guess = ibeta_inv((double)a_, (double)b_, 0.5);
  153. unsigned current_digits = 14;
  154. mpfr_float f(0, current_digits), f1(0, current_digits), delta(1);
  155. while (current_digits < digits10)
  156. {
  157. current_digits *= 2;
  158. scoped_precision sp((std::min)(current_digits, digits10));
  159. mpfr_float a(a_, mpfr_float::default_precision()), b(b_, mpfr_float::default_precision());
  160. guess.precision(mpfr_float::default_precision());
  161. f = boost::math::detail::ibeta_imp(a, b, guess, boost::math::policies::policy<>(), false, true, &f1) - 0.5f;
  162. guess -= f / f1;
  163. }
  164. return guess;
  165. }
  166. /*`
  167. The new performance results look much more promising:
  168. [pre
  169. Method 1 time = 0.591244
  170. Relative error: 2.99991e-1501
  171. Method 2 time = 0.622679
  172. Relative error: 7.55843e-1501
  173. Method 3 time = 0.143393
  174. Relative error: 4.03898e-1501
  175. ]
  176. This time we're 4x faster than `ibeta_inv`, and no doubt that could be improved a little more by carefully
  177. optimising the number of iterations and the method (Halley vs Newton) taken.
  178. Finally, here's the driver code for the above methods:
  179. */
  180. int main()
  181. {
  182. try {
  183. mpfr_float a(10), b(20);
  184. mpfr_float true_value = beta_distribution_median_method_1(a, b, 1700);
  185. stopwatch<std::chrono::high_resolution_clock> my_stopwatch;
  186. mpfr_float v1 = beta_distribution_median_method_1(a, b, 1500);
  187. float hp_time = my_stopwatch.elapsed();
  188. std::cout << "Method 1 time = " << hp_time << std::endl;
  189. std::cout << "Relative error: " << boost::math::relative_difference(v1, true_value) << std::endl;
  190. my_stopwatch.reset();
  191. mpfr_float v2 = beta_distribution_median_method_2(a, b, 1500);
  192. hp_time = my_stopwatch.elapsed();
  193. std::cout << "Method 2 time = " << hp_time << std::endl;
  194. std::cout << "Relative error: " << boost::math::relative_difference(v2, true_value) << std::endl;
  195. my_stopwatch.reset();
  196. mpfr_float v3 = beta_distribution_median_method_3(a, b, 1500);
  197. hp_time = my_stopwatch.elapsed();
  198. std::cout << "Method 3 time = " << hp_time << std::endl;
  199. std::cout << "Relative error: " << boost::math::relative_difference(v3, true_value) << std::endl;
  200. }
  201. catch (const std::exception& e)
  202. {
  203. std::cout << "Found exception with message: " << e.what() << std::endl;
  204. }
  205. return 0;
  206. }
  207. //]