policy_eg_9.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Copyright John Maddock 2007.
  2. // Copyright Paul A. Bristow 2010
  3. // Use, modification and distribution are subject to the
  4. // Boost Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. // Note that this file contains quickbook mark-up as well as code
  7. // and comments, don't change any of the special comment mark-ups!
  8. #include <iostream>
  9. #include <boost/format.hpp>
  10. using std::cout; using std::endl; using std::cerr;
  11. //[policy_eg_9
  12. /*`
  13. The previous example was all well and good, but the custom error handlers
  14. didn't really do much of any use. In this example we'll implement all
  15. the custom handlers and show how the information provided to them can be
  16. used to generate nice formatted error messages.
  17. Each error handler has the general form:
  18. template <class T>
  19. T user_``['error_type]``(
  20. const char* function,
  21. const char* message,
  22. const T& val);
  23. and accepts three arguments:
  24. [variablelist
  25. [[const char* function]
  26. [The name of the function that raised the error, this string
  27. contains one or more %1% format specifiers that should be
  28. replaced by the name of real type T, like float or double.]]
  29. [[const char* message]
  30. [A message associated with the error, normally this
  31. contains a %1% format specifier that should be replaced with
  32. the value of ['value]: however note that overflow and underflow messages
  33. do not contain this %1% specifier (since the value of ['value] is
  34. immaterial in these cases).]]
  35. [[const T& value]
  36. [The value that caused the error: either an argument to the function
  37. if this is a domain or pole error, the tentative result
  38. if this is a denorm or evaluation error, or zero or infinity for
  39. underflow or overflow errors.]]
  40. ]
  41. As before we'll include the headers we need first:
  42. */
  43. #include <boost/math/special_functions.hpp>
  44. /*`
  45. Next we'll implement our own error handlers for each type of error,
  46. starting with domain errors:
  47. */
  48. namespace boost{ namespace math{
  49. namespace policies
  50. {
  51. template <class T>
  52. T user_domain_error(const char* function, const char* message, const T& val)
  53. {
  54. /*`
  55. We'll begin with a bit of defensive programming in case function or message are empty:
  56. */
  57. if(function == 0)
  58. function = "Unknown function with arguments of type %1%";
  59. if(message == 0)
  60. message = "Cause unknown with bad argument %1%";
  61. /*`
  62. Next we'll format the name of the function with the name of type T, perhaps double:
  63. */
  64. std::string msg("Error in function ");
  65. msg += (boost::format(function) % typeid(T).name()).str();
  66. /*`
  67. Then likewise format the error message with the value of parameter /val/,
  68. making sure we output all the potentially significant digits of /val/:
  69. */
  70. msg += ": \n";
  71. int prec = 2 + (std::numeric_limits<T>::digits * 30103UL) / 100000UL;
  72. // int prec = std::numeric_limits<T>::max_digits10; // For C++0X Standard Library
  73. msg += (boost::format(message) % boost::io::group(std::setprecision(prec), val)).str();
  74. /*`
  75. Now we just have to do something with the message, we could throw an
  76. exception, but for the purposes of this example we'll just dump the message
  77. to std::cerr:
  78. */
  79. std::cerr << msg << std::endl;
  80. /*`
  81. Finally the only sensible value we can return from a domain error is a NaN:
  82. */
  83. return std::numeric_limits<T>::quiet_NaN();
  84. }
  85. /*`
  86. Pole errors are essentially a special case of domain errors,
  87. so in this example we'll just return the result of a domain error:
  88. */
  89. template <class T>
  90. T user_pole_error(const char* function, const char* message, const T& val)
  91. {
  92. return user_domain_error(function, message, val);
  93. }
  94. /*`
  95. Overflow errors are very similar to domain errors, except that there's
  96. no %1% format specifier in the /message/ parameter:
  97. */
  98. template <class T>
  99. T user_overflow_error(const char* function, const char* message, const T& val)
  100. {
  101. if(function == 0)
  102. function = "Unknown function with arguments of type %1%";
  103. if(message == 0)
  104. message = "Result of function is too large to represent";
  105. std::string msg("Error in function ");
  106. msg += (boost::format(function) % typeid(T).name()).str();
  107. msg += ": \n";
  108. msg += message;
  109. std::cerr << msg << std::endl;
  110. // Value passed to the function is an infinity, just return it:
  111. return val;
  112. }
  113. /*`
  114. Underflow errors are much the same as overflow:
  115. */
  116. template <class T>
  117. T user_underflow_error(const char* function, const char* message, const T& val)
  118. {
  119. if(function == 0)
  120. function = "Unknown function with arguments of type %1%";
  121. if(message == 0)
  122. message = "Result of function is too small to represent";
  123. std::string msg("Error in function ");
  124. msg += (boost::format(function) % typeid(T).name()).str();
  125. msg += ": \n";
  126. msg += message;
  127. std::cerr << msg << std::endl;
  128. // Value passed to the function is zero, just return it:
  129. return val;
  130. }
  131. /*`
  132. Denormalised results are much the same as underflow:
  133. */
  134. template <class T>
  135. T user_denorm_error(const char* function, const char* message, const T& val)
  136. {
  137. if(function == 0)
  138. function = "Unknown function with arguments of type %1%";
  139. if(message == 0)
  140. message = "Result of function is denormalised";
  141. std::string msg("Error in function ");
  142. msg += (boost::format(function) % typeid(T).name()).str();
  143. msg += ": \n";
  144. msg += message;
  145. std::cerr << msg << std::endl;
  146. // Value passed to the function is denormalised, just return it:
  147. return val;
  148. }
  149. /*`
  150. Which leaves us with evaluation errors: these occur when an internal
  151. error occurs that prevents the function being fully evaluated.
  152. The parameter /val/ contains the closest approximation to the result
  153. found so far:
  154. */
  155. template <class T>
  156. T user_evaluation_error(const char* function, const char* message, const T& val)
  157. {
  158. if(function == 0)
  159. function = "Unknown function with arguments of type %1%";
  160. if(message == 0)
  161. message = "An internal evaluation error occurred with "
  162. "the best value calculated so far of %1%";
  163. std::string msg("Error in function ");
  164. msg += (boost::format(function) % typeid(T).name()).str();
  165. msg += ": \n";
  166. int prec = 2 + (std::numeric_limits<T>::digits * 30103UL) / 100000UL;
  167. // int prec = std::numeric_limits<T>::max_digits10; // For C++0X Standard Library
  168. msg += (boost::format(message) % boost::io::group(std::setprecision(prec), val)).str();
  169. std::cerr << msg << std::endl;
  170. // What do we return here? This is generally a fatal error, that should never occur,
  171. // so we just return a NaN for the purposes of the example:
  172. return std::numeric_limits<T>::quiet_NaN();
  173. }
  174. } // policies
  175. }} // boost::math
  176. /*`
  177. Now we'll need to define a suitable policy that will call these handlers,
  178. and define some forwarding functions that make use of the policy:
  179. */
  180. namespace mymath
  181. { // unnamed.
  182. using namespace boost::math::policies;
  183. typedef policy<
  184. domain_error<user_error>,
  185. pole_error<user_error>,
  186. overflow_error<user_error>,
  187. underflow_error<user_error>,
  188. denorm_error<user_error>,
  189. evaluation_error<user_error>
  190. > user_error_policy;
  191. BOOST_MATH_DECLARE_SPECIAL_FUNCTIONS(user_error_policy)
  192. } // unnamed namespace
  193. /*`
  194. We now have a set of forwarding functions, defined in namespace mymath,
  195. that all look something like this:
  196. ``
  197. template <class RealType>
  198. inline typename boost::math::tools::promote_args<RT>::type
  199. tgamma(RT z)
  200. {
  201. return boost::math::tgamma(z, user_error_policy());
  202. }
  203. ``
  204. So that when we call `mymath::tgamma(z)` we really end up calling
  205. `boost::math::tgamma(z, user_error_policy())`, and any
  206. errors will get directed to our own error handlers:
  207. */
  208. int main()
  209. {
  210. // Raise a domain error:
  211. cout << "Result of erf_inv(-10) is: "
  212. << mymath::erf_inv(-10) << std::endl << endl;
  213. // Raise a pole error:
  214. cout << "Result of tgamma(-10) is: "
  215. << mymath::tgamma(-10) << std::endl << endl;
  216. // Raise an overflow error:
  217. cout << "Result of tgamma(3000) is: "
  218. << mymath::tgamma(3000) << std::endl << endl;
  219. // Raise an underflow error:
  220. cout << "Result of tgamma(-190.5) is: "
  221. << mymath::tgamma(-190.5) << std::endl << endl;
  222. // Unfortunately we can't predicably raise a denormalised
  223. // result, nor can we raise an evaluation error in this example
  224. // since these should never really occur!
  225. } // int main()
  226. /*`
  227. Which outputs:
  228. [pre
  229. Error in function boost::math::erf_inv<double>(double, double):
  230. Argument outside range \[-1, 1\] in inverse erf function (got p=-10).
  231. Result of erf_inv(-10) is: 1.#QNAN
  232. Error in function boost::math::tgamma<long double>(long double):
  233. Evaluation of tgamma at a negative integer -10.
  234. Result of tgamma(-10) is: 1.#QNAN
  235. Error in function boost::math::tgamma<long double>(long double):
  236. Result of tgamma is too large to represent.
  237. Error in function boost::math::tgamma<double>(double):
  238. Result of function is too large to represent
  239. Result of tgamma(3000) is: 1.#INF
  240. Error in function boost::math::tgamma<long double>(long double):
  241. Result of tgamma is too large to represent.
  242. Error in function boost::math::tgamma<long double>(long double):
  243. Result of tgamma is too small to represent.
  244. Result of tgamma(-190.5) is: 0
  245. ]
  246. Notice how some of the calls result in an error handler being called more
  247. than once, or for more than one handler to be called: this is an artefact
  248. of the fact that many functions are implemented in terms of one or more
  249. sub-routines each of which may have it's own error handling. For example
  250. `tgamma(-190.5)` is implemented in terms of `tgamma(190.5)` - which overflows -
  251. the reflection formula for `tgamma` then notices that it is dividing by
  252. infinity and so underflows.
  253. */
  254. //] //[/policy_eg_9]