special_tut.qbk 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. [section:special_tut Tutorial: How to Write a New Special Function]
  2. [section:special_tut_impl Implementation]
  3. In this section, we'll provide a "recipe" for adding a new special function to this library to make life easier for
  4. future authors wishing to contribute. We'll assume the function returns a single floating-point result, and takes
  5. two floating-point arguments. For the sake of exposition we'll give the function the name [~my_special].
  6. Normally, the implementation of such a function is split into two layers - a public user layer, and an internal
  7. implementation layer that does the actual work.
  8. The implementation layer is declared inside a `detail` namespace and has a simple signature:
  9. namespace boost { namespace math { namespace detail {
  10. template <class T, class Policy>
  11. T my_special_imp(const T& a, const T&b, const Policy& pol)
  12. {
  13. /* Implementation goes here */
  14. }
  15. }}} // namespaces
  16. We'll come back to what can go inside the implementation later, but first lets look at the user layer.
  17. This consists of two overloads of the function, with and without a __Policy argument:
  18. namespace boost{ namespace math{
  19. template <class T, class U>
  20. typename tools::promote_args<T, U>::type my_special(const T& a, const U& b);
  21. template <class T, class U, class Policy>
  22. typename tools::promote_args<T, U>::type my_special(const T& a, const U& b, const Policy& pol);
  23. }} // namespaces
  24. Note how each argument has a different template type - this allows for mixed type arguments - the return
  25. type is computed from a traits class and is the "common type" of all the arguments after any integer
  26. arguments have been promoted to type `double`.
  27. The implementation of the non-policy overload is trivial:
  28. namespace boost{ namespace math{
  29. template <class T, class U>
  30. inline typename tools::promote_args<T, U>::type my_special(const T& a, const U& b)
  31. {
  32. // Simply forward with a default policy:
  33. return my_special(a, b, policies::policy<>();
  34. }
  35. }} // namespaces
  36. The implementation of the other overload is somewhat more complex, as there's some meta-programming to do,
  37. but from a runtime perspective is still a one-line forwarding function. Here it is with comments explaining
  38. what each line does:
  39. namespace boost{ namespace math{
  40. template <class T, class U, class Policy>
  41. inline typename tools::promote_args<T, U>::type my_special(const T& a, const U& b, const Policy& pol)
  42. {
  43. //
  44. // We've found some standard library functions to misbehave if any FPU exception flags
  45. // are set prior to their call, this code will clear those flags, then reset them
  46. // on exit:
  47. //
  48. BOOST_FPU_EXCEPTION_GUARD
  49. //
  50. // The type of the result - the common type of T and U after
  51. // any integer types have been promoted to double:
  52. //
  53. typedef typename tools::promote_args<T, U>::type result_type;
  54. //
  55. // The type used for the calculation. This may be a wider type than
  56. // the result in order to ensure full precision:
  57. //
  58. typedef typename policies::evaluation<result_type, Policy>::type value_type;
  59. //
  60. // The type of the policy to forward to the actual implementation.
  61. // We disable promotion of float and double as that's [possibly]
  62. // happened already in the line above. Also reset to the default
  63. // any policies we don't use (reduces code bloat if we're called
  64. // multiple times with differing policies we don't actually use).
  65. // Also normalise the type, again to reduce code bloat in case we're
  66. // called multiple times with functionally identical policies that happen
  67. // to be different types.
  68. //
  69. typedef typename policies::normalise<
  70. Policy,
  71. policies::promote_float<false>,
  72. policies::promote_double<false>,
  73. policies::discrete_quantile<>,
  74. policies::assert_undefined<> >::type forwarding_policy;
  75. //
  76. // Whew. Now we can make the actual call to the implementation.
  77. // Arguments are explicitly cast to the evaluation type, and the result
  78. // passed through checked_narrowing_cast which handles things like overflow
  79. // according to the policy passed:
  80. //
  81. return policies::checked_narrowing_cast<result_type, forwarding_policy>(
  82. detail::my_special_imp(
  83. static_cast<value_type>(a),
  84. static_cast<value_type>(x),
  85. forwarding_policy()),
  86. "boost::math::my_special<%1%>(%1%, %1%)");
  87. }
  88. }} // namespaces
  89. We're now almost there, we just need to flesh out the details of the implementation layer:
  90. namespace boost { namespace math { namespace detail {
  91. template <class T, class Policy>
  92. T my_special_imp(const T& a, const T&b, const Policy& pol)
  93. {
  94. /* Implementation goes here */
  95. }
  96. }}} // namespaces
  97. The following guidelines indicate what (other than basic arithmetic) can go in the implementation:
  98. * Error conditions (for example bad arguments) should be handled by calling one of the
  99. [link math_toolkit.error_handling.finding_more_information policy based error handlers].
  100. * Calls to standard library functions should be made unqualified (this allows argument
  101. dependent lookup to find standard library functions for user-defined floating point
  102. types such as those from __multiprecision). In addition, the macro `BOOST_MATH_STD_USING`
  103. should appear at the start of the function (note no semi-colon afterwards!) so that
  104. all the math functions in `namespace std` are visible in the current scope.
  105. * Calls to other special functions should be made as fully qualified calls, and include the
  106. policy parameter as the last argument, for example `boost::math::tgamma(a, pol)`.
  107. * Where possible, evaluation of series, continued fractions, polynomials, or root
  108. finding should use one of the [link math_toolkit.internals_overview boiler-plate functions]. In any case, after
  109. any iterative method, you should verify that the number of iterations did not exceed the
  110. maximum specified in the __Policy type, and if it did terminate as a result of exceeding the
  111. maximum, then the appropriate error handler should be called (see existing code for examples).
  112. * Numeric constants such as [pi] etc should be obtained via a call to the [link math_toolkit.constants appropriate function],
  113. for example: `constants::pi<T>()`.
  114. * Where tables of coefficients are used (for example for rational approximations), care should be taken
  115. to ensure these are initialized at program startup to ensure thread safety when using user-defined number types.
  116. See for example the use of `erf_initializer` in [@../../include/boost/math/special_functions/erf.hpp erf.hpp].
  117. Here are some other useful internal functions:
  118. [table
  119. [[function][Meaning]]
  120. [[`policies::digits<T, Policy>()`][Returns number of binary digits in T (possible overridden by the policy).]]
  121. [[`policies::get_max_series_iterations<Policy>()`][Maximum number of iterations for series evaluation.]]
  122. [[`policies::get_max_root_iterations<Policy>()`][Maximum number of iterations for root finding.]]
  123. [[`polices::get_epsilon<T, Policy>()`][Epsilon for type T, possibly overridden by the Policy.]]
  124. [[`tools::digits<T>()`][Returns the number of binary digits in T.]]
  125. [[`tools::max_value<T>()`][Equivalent to `std::numeric_limits<T>::max()`]]
  126. [[`tools::min_value<T>()`][Equivalent to `std::numeric_limits<T>::min()`]]
  127. [[`tools::log_max_value<T>()`][Equivalent to the natural logarithm of `std::numeric_limits<T>::max()`]]
  128. [[`tools::log_min_value<T>()`][Equivalent to the natural logarithm of `std::numeric_limits<T>::min()`]]
  129. [[`tools::epsilon<T>()`][Equivalent to `std::numeric_limits<T>::epsilon()`.]]
  130. [[`tools::root_epsilon<T>()`][Equivalent to the square root of `std::numeric_limits<T>::epsilon()`.]]
  131. [[`tools::forth_root_epsilon<T>()`][Equivalent to the forth root of `std::numeric_limits<T>::epsilon()`.]]
  132. ]
  133. [endsect]
  134. [section:special_tut_test Testing]
  135. We work under the assumption that untested code doesn't work, so some tests for your new special function are in order,
  136. we'll divide these up in to 3 main categories:
  137. [h4 Spot Tests]
  138. Spot tests consist of checking that the expected exception is generated when the inputs are in error (or
  139. otherwise generate undefined values), and checking any special values. We can check for expected exceptions
  140. with `BOOST_CHECK_THROW`, so for example if it's a domain error for the last parameter to be outside the range
  141. `[0,1]` then we might have:
  142. BOOST_CHECK_THROW(my_special(0, -0.1), std::domain_error);
  143. BOOST_CHECK_THROW(my_special(0, 1.1), std::domain_error);
  144. When the function has known exact values (typically integer values) we can use `BOOST_CHECK_EQUAL`:
  145. BOOST_CHECK_EQUAL(my_special(1.0, 0.0), 0);
  146. BOOST_CHECK_EQUAL(my_special(1.0, 1.0), 1);
  147. When the function has known values which are not exact (from a floating point perspective) then we can use
  148. `BOOST_CHECK_CLOSE_FRACTION`:
  149. // Assumes 4 epsilon is as close as we can get to a true value of 2Pi:
  150. BOOST_CHECK_CLOSE_FRACTION(my_special(0.5, 0.5), 2 * constants::pi<double>(), std::numeric_limits<double>::epsilon() * 4);
  151. [h4 Independent Test Values]
  152. If the function is implemented by some other known good source (for example Mathematica or it's online versions
  153. [@http://functions.wolfram.com functions.wolfram.com] or [@http://www.wolframalpha.com www.wolframalpha.com]
  154. then it's a good idea to sanity check our implementation by having at least one independendly generated value
  155. for each code branch our implementation may take. To slot these in nicely with our testing framework it's best to
  156. tabulate these like this:
  157. // function values calculated on http://functions.wolfram.com/
  158. static const boost::array<boost::array<T, 3>, 10> my_special_data = {{
  159. {{ SC_(0), SC_(0), SC_(1) }},
  160. {{ SC_(0), SC_(1), SC_(1.26606587775200833559824462521471753760767031135496220680814) }},
  161. /* More values here... */
  162. }};
  163. We'll see how to use this table and the meaning of the `SC_` macro later. One important point
  164. is to make sure that the input values have exact binary representations: so choose values such as
  165. 1.5, 1.25, 1.125 etc. This ensures that if `my_special` is unusually sensitive in one area, that
  166. we don't get apparently large errors just because the inputs are 0.5 ulp in error.
  167. [h4 Random Test Values]
  168. We can generate a large number of test values to check both for future regressions, and for
  169. accumulated rounding or cancellation error in our implementation. Ideally we would use an
  170. independent implementation for this (for example my_special may be defined in directly terms
  171. of other special functions but not implemented that way for performance or accuracy reasons).
  172. Alternatively we may use our own implementation directly, but with any special cases (asymptotic
  173. expansions etc) disabled. We have a set of [link math_toolkit.internals.test_data tools]
  174. to generate test data directly, here's a typical example:
  175. [import ../../example/special_data.cpp]
  176. [special_data_example]
  177. Typically several sets of data will be generated this way, including random values in some "normal"
  178. range, extreme values (very large or very small), and values close to any "interesting" behaviour
  179. of the function (singularities etc).
  180. [h4 The Test File Header]
  181. We split the actual test file into 2 distinct parts: a header that contains the testing code
  182. as a series of function templates, and the actual .cpp test driver that decides which types
  183. are tested, and sets the "expected" error rates for those types. It's done this way because:
  184. * We want to test with both built in floating point types, and with multiprecision types.
  185. However, both compile and runtimes with the latter can be too long for the folks who run
  186. the tests to realistically cope with, so it makes sense to split the test into (at least)
  187. 2 parts.
  188. * The definition of the SC_ macro used in our tables of data may differ depending on what type
  189. we're testing (see below). Again this is largely a matter of managing compile times as large tables
  190. of user-defined-types can take a crazy amount of time to compile with some compilers.
  191. The test header contains 2 functions:
  192. template <class Real, class T>
  193. void do_test(const T& data, const char* type_name, const char* test_name);
  194. template <class T>
  195. void test(T, const char* type_name);
  196. Before implementing those, we'll include the headers we'll need, and provide a default
  197. definition for the SC_ macro:
  198. // A couple of Boost.Test headers in case we need any BOOST_CHECK_* macros:
  199. #include <boost/test/unit_test.hpp>
  200. #include <boost/test/tools/floating_point_comparison.hpp>
  201. // Our function to test:
  202. #include <boost/math/special_functions/my_special.hpp>
  203. // We need boost::array for our test data, plus a few headers from
  204. // libs/math/test that contain our testing machinary:
  205. #include <boost/array.hpp>
  206. #include "functor.hpp"
  207. #include "handle_test_result.hpp"
  208. #include "table_type.hpp"
  209. #ifndef SC_
  210. #define SC_(x) static_cast<typename table_type<T>::type>(BOOST_JOIN(x, L))
  211. #endif
  212. The easiest function to implement is the "test" function which is what we'll be calling
  213. from the test-driver program. It simply includes the files containing the tabular
  214. test data and calls `do_test` function for each table, along with a description of what's
  215. being tested:
  216. template <class T>
  217. void test(T, const char* type_name)
  218. {
  219. //
  220. // The actual test data is rather verbose, so it's in a separate file
  221. //
  222. // The contents are as follows, each row of data contains
  223. // three items, input value a, input value b and my_special(a, b):
  224. //
  225. # include "my_special_1.ipp"
  226. do_test<T>(my_special_1, name, "MySpecial Function: Mathematica Values");
  227. # include "my_special_2.ipp"
  228. do_test<T>(my_special_2, name, "MySpecial Function: Random Values");
  229. # include "my_special_3.ipp"
  230. do_test<T>(my_special_3, name, "MySpecial Function: Very Small Values");
  231. }
  232. The function `do_test` takes each table of data and calculates values for each row
  233. of data, along with statistics for max and mean error etc, most of this is handled
  234. by some boilerplate code:
  235. template <class Real, class T>
  236. void do_test(const T& data, const char* type_name, const char* test_name)
  237. {
  238. // Get the type of each row and each element in the rows:
  239. typedef typename T::value_type row_type;
  240. typedef Real value_type;
  241. // Get a pointer to our function, we have to use a workaround here
  242. // as some compilers require the template types to be explicitly
  243. // specified, while others don't much like it if it is!
  244. typedef value_type (*pg)(value_type, value_type);
  245. #if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)
  246. pg funcp = boost::math::my_special<value_type, value_type>;
  247. #else
  248. pg funcp = boost::math::my_special;
  249. #endif
  250. // Somewhere to hold our results:
  251. boost::math::tools::test_result<value_type> result;
  252. // And some pretty printing:
  253. std::cout << "Testing " << test_name << " with type " << type_name
  254. << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
  255. //
  256. // Test my_special against data:
  257. //
  258. result = boost::math::tools::test_hetero<Real>(
  259. /* First argument is the table */
  260. data,
  261. /* Next comes our function pointer, plus the indexes of it's arguments in the table */
  262. bind_func<Real>(funcp, 0, 1),
  263. /* Then the index of the result in the table - potentially we can test several
  264. related functions this way, each having the same input arguments, and different
  265. output values in different indexes in the table */
  266. extract_result<Real>(2));
  267. //
  268. // Finish off with some boilerplate to check the results were within the expected errors,
  269. // and pretty print the results:
  270. //
  271. handle_test_result(result, data[result.worst()], result.worst(), type_name, "boost::math::my_special", test_name);
  272. }
  273. Now we just need to write the test driver program, at it's most basic it looks something like this:
  274. #include <boost/math/special_functions/math_fwd.hpp>
  275. #include <boost/math/tools/test.hpp>
  276. #include <boost/math/tools/stats.hpp>
  277. #include <boost/type_traits.hpp>
  278. #include <boost/array.hpp>
  279. #include "functor.hpp"
  280. #include "handle_test_result.hpp"
  281. #include "test_my_special.hpp"
  282. BOOST_AUTO_TEST_CASE( test_main )
  283. {
  284. //
  285. // Test each floating point type, plus real_concept.
  286. // We specify the name of each type by hand as typeid(T).name()
  287. // often gives an unreadable mangled name.
  288. //
  289. test(0.1F, "float");
  290. test(0.1, "double");
  291. //
  292. // Testing of long double and real_concept is protected
  293. // by some logic to disable these for unsupported
  294. // or problem compilers.
  295. //
  296. #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
  297. test(0.1L, "long double");
  298. #ifndef BOOST_MATH_NO_REAL_CONCEPT_TESTS
  299. #if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))
  300. test(boost::math::concepts::real_concept(0.1), "real_concept");
  301. #endif
  302. #endif
  303. #else
  304. std::cout << "<note>The long double tests have been disabled on this platform "
  305. "either because the long double overloads of the usual math functions are "
  306. "not available at all, or because they are too inaccurate for these tests "
  307. "to pass.</note>" << std::cout;
  308. #endif
  309. }
  310. That's almost all there is too it - except that if the above program is run it's very likely that
  311. all the tests will fail as the default maximum allowable error is 1 epsilon. So we'll
  312. define a function (don't forget to call it from the start of the `test_main` above) to
  313. up the limits to something sensible, based both on the function we're calling and on
  314. the particular tests plus the platform and compiler:
  315. void expected_results()
  316. {
  317. //
  318. // Define the max and mean errors expected for
  319. // various compilers and platforms.
  320. //
  321. const char* largest_type;
  322. #ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
  323. if(boost::math::policies::digits<double, boost::math::policies::policy<> >() == boost::math::policies::digits<long double, boost::math::policies::policy<> >())
  324. {
  325. largest_type = "(long\\s+)?double|real_concept";
  326. }
  327. else
  328. {
  329. largest_type = "long double|real_concept";
  330. }
  331. #else
  332. largest_type = "(long\\s+)?double";
  333. #endif
  334. //
  335. // We call add_expected_result for each error rate we wish to adjust, these tell
  336. // handle_test_result what level of error is acceptable. We can have as many calls
  337. // to add_expected_result as we need, each one establishes a rule for acceptable error
  338. // with rules set first given preference.
  339. //
  340. add_expected_result(
  341. /* First argument is a regular expression to match against the name of the compiler
  342. set in BOOST_COMPILER */
  343. ".*",
  344. /* Second argument is a regular expression to match against the name of the
  345. C++ standard library as set in BOOST_STDLIB */
  346. ".*",
  347. /* Third argument is a regular expression to match against the name of the
  348. platform as set in BOOST_PLATFORM */
  349. ".*",
  350. /* Forth argument is the name of the type being tested, normally we will
  351. only need to up the acceptable error rate for the widest floating
  352. point type being tested */
  353. largest_real,
  354. /* Fifth argument is a regular expression to match against
  355. the name of the group of data being tested */
  356. "MySpecial Function:.*Small.*",
  357. /* Sixth argument is a regular expression to match against the name
  358. of the function being tested */
  359. "boost::math::my_special",
  360. /* Seventh argument is the maximum allowable error expressed in units
  361. of machine epsilon passed as a long integer value */
  362. 50,
  363. /* Eighth argument is the maximum allowable mean error expressed in units
  364. of machine epsilon passed as a long integer value */
  365. 20);
  366. }
  367. [h4 Testing Multiprecision Types]
  368. Testing of multiprecision types is handled by the test drivers in libs/multiprecision/test/math,
  369. please refer to these for examples. Note that these tests are run only occationally as they take
  370. a lot of CPU cycles to build and run.
  371. [h4 Improving Compile Times]
  372. As noted above, these test programs can take a while to build as we're instantiating a lot of templates
  373. for several different types, and our test runners are already stretched to the limit, and probably
  374. using outdated "spare" hardware. There are two things we can do to speed things up:
  375. * Use a precompiled header.
  376. * Use separate compilation of our special function templates.
  377. We can make these changes by changing the list of includes from:
  378. #include <boost/math/special_functions/math_fwd.hpp>
  379. #include <boost/math/tools/test.hpp>
  380. #include <boost/math/tools/stats.hpp>
  381. #include <boost/type_traits.hpp>
  382. #include <boost/array.hpp>
  383. #include "functor.hpp"
  384. #include "handle_test_result.hpp"
  385. To just:
  386. #include <pch_light.hpp>
  387. And changing
  388. #include <boost/math/special_functions/my_special.hpp>
  389. To:
  390. #include <boost/math/special_functions/math_fwd.hpp>
  391. The Jamfile target that builds the test program will need the targets
  392. test_instances//test_instances pch_light
  393. adding to it's list of source dependencies (see the Jamfile for examples).
  394. Finally the project in libs/math/test/test_instances will need modifying
  395. to instantiate function `my_special`.
  396. These changes should be made last, when `my_special` is stable and the code is in Trunk.
  397. [h4 Concept Checks]
  398. Our concept checks verify that your function's implementation makes no assumptions that aren't
  399. required by our [link math_toolkit.real_concepts Real number conceptual requirements]. They also
  400. check for various common bugs and programming traps that we've fallen into over time. To
  401. add your function to these tests, edit libs/math/test/compile_test/instantiate.hpp to add
  402. calls to your function: there are 7 calls to each function, each with a different purpose.
  403. Search for something like "ibeta" or "gamm_p" and follow their examples.
  404. [endsect]
  405. [endsect]
  406. [/
  407. Copyright 2013 John Maddock.
  408. Distributed under the Boost Software License, Version 1.0.
  409. (See accompanying file LICENSE_1_0.txt or copy at
  410. http://www.boost.org/LICENSE_1_0.txt).
  411. ]