Imported Upstream version 1.72.0
[platform/upstream/boost.git] / libs / math / doc / constants / constants.qbk
1 [mathpart constants..Mathematical Constants]
2
3 [section:constants_intro Introduction]
4
5 Boost.Math provides a collection of mathematical constants.
6
7 [h4 Why use Boost.Math mathematical constants?]
8
9 * Readable. For the very many jobs just using built-in like `double`, you can just write expressions like
10 ``double area = pi * r * r;``
11 (If that's all you want, jump direct to [link math_toolkit.tutorial.non_templ use in non-template code]!)
12 * Effortless - avoiding a search of reference sources.
13 * Usable with both builtin floating point types, and user-defined, possibly extended precision, types such as
14 NTL, MPFR/GMP, mp_float: in the latter case the constants are computed to the necessary precision and then cached.
15 * Accurate - ensuring that the values are as accurate as possible for the
16 chosen floating-point type
17   * No loss of accuracy from repeated rounding of intermediate computations.
18   * Result is computed with higher precision and only rounded once.
19   * Less risk of inaccurate result from functions pow, trig and log at [@http://en.wikipedia.org/wiki/Corner_case corner cases].
20   * Less risk of [@http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html cancellation error].
21 * Portable - as possible between different systems using different floating-point precisions:
22 see [link math_toolkit.tutorial.templ use in template code].
23 * Tested - by comparison with other published sources, or separately computed at long double precision.
24 * Faster - can avoid (re-)calculation at runtime.
25   * If the value returned is a builtin type then it's returned by value as a `constexpr` (C++11 feature, if available).
26   * If the value is computed and cached (or constructed from a string representation and cached), then it's returned by constant reference.
27
28   This can be 
29 significant if:
30     * Functions pow, trig or log are used.
31     * Inside an inner loop.
32     * Using a high-precision UDT like __multiprecision.
33     * Compiler optimizations possible with built-in types, especially `double`, are not available.
34
35 [endsect] [/section:intro Introduction]
36
37 [section:tutorial Tutorial]
38
39 [section:non_templ Use in non-template code]
40
41 When using the math constants at your chosen fixed precision in non-template code,
42 you can simply add a `using namespace` declaration, for example,
43 `using namespace boost::math::double_constants`,
44 to make the constants of the correct precision for your code
45 visible in the current scope, and then use each constant ['as a simple variable - sans brackets]:
46
47    #include <boost/math/constants/constants.hpp>
48
49    double area(double r)
50    {
51       using namespace boost::math::double_constants;
52       return pi * r * r;
53    }
54
55 Had our function been written as taking a `float` rather than a `double`,
56 we could have written instead:
57
58    #include <boost/math/constants/constants.hpp>
59
60    float area(float r)
61    {
62       using namespace boost::math::float_constants;
63       return pi * r * r;
64    }
65
66 Likewise, constants that are suitable for use at `long double` precision
67 are available in the namespace `boost::math::long_double_constants`.
68
69 You can see the full list of available constants at [link math_toolkit.constants].
70
71 Some examples of using constants are at [@../../example/constants_eg1.cpp constants_eg1].
72
73 [endsect] [/section:non_templ Use in non-template code]
74
75 [section:templ Use in template code]
76
77 When using the constants inside a function template, we need to ensure that
78 we use a constant of the correct precision for our template parameters.
79 We can do this by calling the function-template versions, `pi<FPType>()`, of the constants
80 like this:
81
82    #include <boost/math/constants/constants.hpp>
83
84    template <class Real>
85    Real area(Real r)
86    {
87       using namespace boost::math::constants;
88       return pi<Real>() * r * r;
89    }
90
91 Although this syntax is a little less "cute" than the non-template version,
92 the code is no less efficient
93 (at least for the built-in types `float`, `double` and `long double`) :
94 the function template versions of the constants are simple inline functions that
95 return a constant of the correct precision for the type used. In addition, these
96 functions are declared `constexp` for those compilers that support this, allowing
97 the result to be used in constant-expressions provided the template argument is a literal type.
98
99 [tip Keep in mind the difference between the variable version,
100 just `pi`, and the template-function version:
101 the template-function requires both a <[~floating-point-type]>
102 and function call `()` brackets, for example: `pi<double>()`.
103 You cannot write `double p = pi<>()`, nor `double p = pi()`.]
104
105 [note You can always use [*both] variable and template-function versions
106 [*provided calls are fully qualified], for example:
107 ``
108 double my_pi1 = boost::math::constants::pi<double>();
109 double my_pi2 = boost::math::double_constants::pi;
110 ``
111 ]
112
113 [warning It may be tempting to simply define
114 ``
115 using namespace boost::math::double_constants;
116 using namespace boost::math::constants;
117 ``
118 but if you do define two namespaces, this will, of course, create ambiguity!
119 ``
120 double my_pi = pi(); // error C2872: 'pi' : ambiguous symbol
121 double my_pi2 = pi; // Context does not allow for disambiguation of overloaded function
122 ``
123 Although the  mistake above is fairly obvious,
124 it is also not too difficult to do this accidentally, or worse, create it in someone elses code.
125
126 Therefore is it prudent to avoid this risk by [*localising the scope of such definitions], as shown above.]
127
128 [tip Be very careful with the type provided as parameter.
129 For example, providing an [*integer] instead of a floating-point type can be disastrous (a C++ feature).
130
131 ``cout << "Area = " << area(2) << endl; // Area = 12!!!``
132
133 You should get a compiler warning
134 [pre
135 warning : 'return' : conversion from 'double' to 'int', possible loss of data
136 ] [/pre]
137 Failure to heed this warning can lead to very wrong answers!
138
139 You can also avoid this by being explicit about the type of `Area`.
140 ``cout << "Area = " << area<double>(2) << endl; // Area = 12.566371``
141 ]
142
143 [endsect] [/section:templ Use in template code]
144
145 [section:user_def Use With User-Defined Types]
146
147 The most common example of a high-precision user-defined type will probably be __multiprecision.
148
149 The syntax for using the function-call constants with user-defined types is the same
150 as it is in the template class, which is to say we use:
151
152    #include <boost/math/constants/constants.hpp>
153
154    boost::math::constants::pi<UserDefinedType>();
155
156 For example:
157
158   boost::math::constants::pi<boost::multiprecision::cpp_dec_float_50>();
159
160 giving [pi] with a precision of 50 decimal digits.
161
162 However, since the precision of the user-defined type may be much greater than that
163 of the built-in floating point types, how the value returned is created is as follows:
164
165 * If the precision of the type is known at compile time:
166    * If the precision is less than or equal to that of a `float` and the type is constructable from a `float`
167      then our code returns a `float` literal.  If the user-defined type is a literal type
168      then the function call that returns the constant will be a `constexp`.
169    * If the precision is less than or equal to that of a `double` and the type is constructable from a `double`
170      then our code returns a `double` literal.  If the user-defined type is a literal type
171      then the function call that returns the constant will be a `constexp`.
172    * If the precision is less than or equal to that of a `long double` and the type is constructable from a `long double`
173      then our code returns a `long double` literal.  If the user-defined type is a literal type
174      then the function call that returns the constant will be a `constexp`.
175    * If the precision is less than or equal to that of a `__float128` (and the compiler supports such a type)
176      and the type is constructable from a `__float128`
177      then our code returns a `__float128` literal.  If the user-defined type is a literal type
178      then the function call that returns the constant will be a `constexp`.
179    * If the precision is less than 100 decimal digits, then the constant will be constructed
180       (just the once, then cached in a thread-safe manner) from a string representation of the constant.
181       In this case the value is returned as a const reference to the cached value.
182    * Otherwise the value is computed (just once, then cached in a thread-safe manner).
183      In this case the value is returned as a const reference to the cached value.
184 * If the precision is unknown at compile time then:
185    * If the runtime precision (obtained from a call to `boost::math::tools::digits<T>()`) is
186      less than 100 decimal digits, then the constant is constructed "on the fly" from the string
187      representation of the constant.
188    * Otherwise the value is constructed "on the fly" by calculating then value of the constant
189      using the current default precision of the type.  Note that this can make use of the constants
190      rather expensive.
191
192 In addition, it is possible to pass a `Policy` type as a second template argument, and use this to control
193 the precision:
194
195    #include <boost/math/constants/constants.hpp>
196
197    typedef boost::math::policies::policy<boost::math::policies::digits2<80> > my_policy_type;
198    boost::math::constants::pi<MyType, my_policy_type>();
199
200 [note Boost.Math doesn't know how to control the internal precision of `MyType`, the policy
201 just controls how the selection process above is carried out, and the calculation precision
202 if the result is computed.]
203
204 It is also possible to control which method is used to construct the constant by specialising
205 the traits class `construction_traits`:
206
207    namespace boost{ namespace math{ namespace constant{
208
209    template <class T, class Policy>
210    struct construction_traits
211    {
212       typedef mpl::int_<N> type;
213    };
214
215    }}} // namespaces
216
217 Where ['N] takes one of the following values:
218
219 [table
220 [[['N]][Meaning]]
221 [[0][The precision is unavailable at compile time;
222 either construct from a decimal digit string or calculate on the fly depending upon the runtime precision.]]
223 [[1][Return a float precision constant.]]
224 [[2][Return a double precision constant.]]
225 [[3][Return a long double precision constant.]]
226 [[4][Construct the result from the string representation, and cache the result.]]
227 [[Any other value ['N]][Sets the compile time precision to ['N] bits.]]
228 ]
229
230 [h5 Custom Specializing a constant]
231
232 In addition, for user-defined types that need special handling, it's possible to partially-specialize
233 the internal structure used by each constant.  For example, suppose we're using the C++ wrapper around MPFR
234 `mpfr_class`: this has its own representation of Pi which we may well wish to use in place of the above
235 mechanism.  We can achieve this by specialising the class template `boost::math::constants::detail::constant_pi`:
236
237    namespace boost{ namespace math{ namespace constants{ namespace detail{
238
239    template<>
240    struct constant_pi<mpfr_class>
241    {
242       template<int N>
243       static mpfr_class get(const mpl::int_<N>&)
244       {
245          // The template param N is one of the values in the table above,
246          // we can either handle all cases in one as is the case here,
247          // or overload "get" for the different options.
248          mpfr_class result;
249          mpfr_const_pi(result.get_mpfr_t(), GMP_RNDN);
250          return result;
251       }
252    };
253
254    }}}} // namespaces
255
256 [h5 Diagnosing what meta-programmed code is doing]
257
258 Finally, since it can be tricky to diagnose what meta-programmed code is doing, there is a
259 diagnostic routine that prints information about how this library will handle a specific type,
260 it can be used like this:
261
262    #include <boost/math/constants/info.hpp>
263
264    int main()
265    {
266       boost::math::constants::print_info_on_type<MyType>();
267    }
268
269 If you wish, you can also pass an optional std::ostream argument to the `print_info_on_type` function.
270 Typical output for a user-defined type looks like this:
271
272 [pre
273 Information on the Implementation and Handling of
274 Mathematical Constants for Type class boost::math::concepts::real_concept
275
276 Checking for std::numeric_limits<class boost::math::concepts::real_concept> specialisation: no
277 boost::math::policies::precision<class boost::math::concepts::real_concept, Policy>
278 reports that there is no compile type precision available.
279 boost::math::tools::digits<class boost::math::concepts::real_concept>()
280 reports that the current runtime precision is
281 53 binary digits.
282 No compile time precision is available, the construction method
283 will be decided at runtime and results will not be cached
284 - this may lead to poor runtime performance.
285 Current runtime precision indicates that
286 the constant will be constructed from a string on each call.
287 ]
288
289 [endsect] [/section:user_def Use With User Defined Types]
290
291 [endsect] [/section:tutorial Tutorial]
292
293 [section:constants The Mathematical Constants]
294
295 This section lists the mathematical constants, their use(s) (and sometimes rationale for their inclusion).
296 [table Mathematical Constants
297 [[name] [formula] [Value (6 decimals)] [Uses and Rationale]]
298 [[[*Rational fractions]] [] [] [] ]
299 [[half] [1/2] [0.5] [] ]
300 [[third] [1/3] [0.333333] [] ]
301 [[two_thirds] [2/3] [0.66667] [] ]
302 [[three_quarters] [3/4] [0.75] [] ]
303
304 [[[*two and related]] [] [] [] ]
305 [[root_two] [[radic]2] [1.41421] [Equivalent to POSIX constant M_SQRT2] ]
306 [[root_three] [[radic]3] [1.73205] [] ]
307 [[half_root_two] [[radic]2 /2] [0.707106] [] ]
308 [[ln_two] [ln(2)] [0.693147] [Equivalent to POSIX constant M_LN2] ]
309 [[ln_ten] [ln(10)] [2.30258] [Equivalent to POSIX constant M_LN10] ]
310 [[ln_ln_two] [ln(ln(2))] [-0.366512] [Gumbel distribution median] ]
311 [[root_ln_four] [[radic]ln(4)] [1.177410] [] ]
312 [[one_div_root_two] [1/[radic]2] [0.707106] [Equivalent to POSIX constant M_SQRT1_2] ]
313
314 [[[*[pi] and related]] [] [] [] ]
315 [[pi] [pi] [3.14159] [Ubiquitous. Archimedes constant [@http://en.wikipedia.org/wiki/Pi [pi]].  Equivalent to POSIX constant M_PI]]
316 [[half_pi] [[pi]/2] [1.570796] [Equivalent to POSIX constant M_PI2] ]
317 [[third_pi] [[pi]/3] [1.04719] [] ]
318 [[quarter_pi] [[pi]/4] [0.78539816] [Equivalent to POSIX constant M_PI_4] ]
319 [[sixth_pi] [[pi]/6] [0.523598] [] ]
320 [[two_pi] [2[pi]] [6.28318] [Many uses, most simply, circumference of a circle]]
321 [[two_thirds_pi] [2/3 [pi]] [2.09439] [[@http://en.wikipedia.org/wiki/Sphere#Volume_of_a_sphere volume of a hemi-sphere] = 4/3 [pi] r[cubed]]]
322 [[three_quarters_pi] [3/4 [pi]] [2.35619] [ = 3/4 [pi] ]]
323 [[four_thirds_pi] [4/3 [pi]] [4.18879] [[@http://en.wikipedia.org/wiki/Sphere#Volume_of_a_sphere volume of a sphere] = 4/3 [pi] r[cubed]]]
324 [[one_div_two_pi] [1/(2[pi])] [1.59155] [Widely used]]
325 [[root_pi] [[radic][pi]][1.77245] [Widely used]]
326 [[root_half_pi] [[radic] [pi]/2] [1.25331] [Widely used]]
327 [[root_two_pi][[radic] [pi]*2] [2.50662] [Widely used]]
328 [[one_div_pi] [1/[pi]] [0.31830988] [Equivalent to POSIX constant M_1_PI] ]
329 [[two_div_pi] [2/[pi]] [0.63661977] [Equivalent to POSIX constant M_2_PI] ]
330 [[one_div_root_pi] [1/[radic][pi]] [0.564189] [] ]
331 [[two_div_root_pi] [2/[radic][pi]] [1.128379] [Equivalent to POSIX constant M_2_SQRTPI] ]
332 [[one_div_root_two_pi] [1/[radic](2[pi])] [0.398942] [] ]
333 [[root_one_div_pi] [[radic](1/[pi]] [0.564189] [] ]
334 [[pi_minus_three] [[pi]-3] [0.141593] [] ]
335 [[four_minus_pi] [4 -[pi]] [0.858407] [] ]
336 [[pi_pow_e] [[pi][super e]] [22.4591] [] ]
337
338 [[pi_sqr] [[pi][super 2]] [9.86960] [] ]
339 [[pi_sqr_div_six] [[pi][super 2]/6] [1.64493] [] ]
340 [[pi_cubed] [[pi][super 3]] [31.00627] [] ]
341 [[cbrt_pi] [[radic][super 3] [pi]] [1.46459] [] ]
342 [[one_div_cbrt_pi] [1/[radic][super 3] [pi]] [0.682784] [] ]
343
344 [[[*Euler's e and related]] [] [] [] ]
345 [[e] [e] [2.71828] [[@http://en.wikipedia.org/wiki/E_(mathematical_constant) Euler's constant e], equivalent to POSIX constant M_E] ]
346 [[exp_minus_half] [e [super -1/2]] [0.606530] [] ]
347 [[e_pow_pi] [e [super [pi]]] [23.14069] [] ]
348 [[root_e] [[radic] e] [1.64872] [] ]
349 [[log10_e] [log10(e)] [0.434294] [Equivalent to POSIX constant M_LOG10E] ]
350 [[one_div_log10_e] [1/log10(e)] [2.30258] [] ]
351 [[log2_e] [log[sub 2](e)] [1.442695] [This is the same as 1/ln(2) and is equivalent to POSIX constant M_LOG2E] ]
352
353 [[[*Trigonometric]] [] [] [] ]
354 [[degree] [radians = [pi] / 180] [0.017453] [] ]
355 [[radian] [degrees = 180 / [pi]] [57.2957] [] ]
356 [[sin_one] [sin(1)] [0.841470] [] ]
357 [[cos_one] [cos(1)] [0.54030] [] ]
358 [[sinh_one] [sinh(1)] [1.17520] [] ]
359 [[cosh_one] [cosh(1)] [1.54308] [] ]
360
361 [[[*Phi]] [ Phidias golden ratio] [[@http://en.wikipedia.org/wiki/Golden_ratio Phidias golden ratio]] [] ]
362 [[phi] [(1 + [radic]5) /2] [1.61803] [finance] ]
363 [[ln_phi] [ln([phi])] [0.48121] [] ]
364 [[one_div_ln_phi] [1/ln([phi])] [2.07808] [] ]
365
366 [[[*Euler's Gamma]] [] [] [] ]
367 [[euler] [euler] [0.577215] [[@http://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant Euler-Mascheroni gamma constant]] ]
368 [[one_div_euler] [1/euler] [1.73245] [] ]
369 [[euler_sqr] [euler[super 2]] [0.333177] [] ]
370
371 [[[*Misc]] [] [] [] ]
372 [[zeta_two] [[zeta](2)] [1.64493] [[@http://en.wikipedia.org/wiki/Riemann_zeta_function Riemann zeta function]] ]
373 [[zeta_three] [[zeta](3)] [1.20205] [[@http://en.wikipedia.org/wiki/Riemann_zeta_function Riemann zeta function]] ]
374 [[catalan] [['K]] [0.915965] [[@http://mathworld.wolfram.com/CatalansConstant.html Catalan (or Glaisher) combinatorial constant] ]]
375 [[glaisher] [['A]] [1.28242] [[@https://oeis.org/A074962/constant Decimal expansion of Glaisher-Kinkelin constant] ]]
376 [[khinchin] [['k]] [2.685452] [[@https://oeis.org/A002210/constant Decimal expansion of Khinchin constant] ]]
377
378 [[extreme_value_skewness] [12[radic]6 [zeta](3)/ [pi][super 3]] [1.139547] [Extreme value distribution] ]
379 [[rayleigh_skewness] [2[radic][pi]([pi]-3)/(4 - [pi])[super 3/2]] [0.631110] [Rayleigh distribution skewness] ]
380 [[rayleigh_kurtosis_excess] [-(6[pi][super 2]-24[pi]+16)/(4-[pi])[super 2]] [0.245089] [[@http://en.wikipedia.org/wiki/Rayleigh_distribution Rayleigh distribution kurtosis excess]] ]
381 [[rayleigh_kurtosis] [3+(6[pi][super 2]-24[pi]+16)/(4-[pi])[super 2]] [3.245089] [Rayleigh distribution kurtosis] ]
382
383 ] [/table]
384
385
386 [note Integer values are [*not included] in this list of math constants, however interesting,
387 because they can be so easily and exactly constructed, even for UDT, for example: `static_cast<cpp_float>(42)`.]
388
389 [tip If you know the approximate value of the constant, you can search for the value to find Boost.Math chosen name in this table.]
390 [tip Bernoulli numbers are available at __bernoulli_numbers.]
391 [tip Factorials are available at __factorial.]
392
393 [endsect]  [/section:constants The constants]
394
395 [section:new_const Defining New Constants]
396
397 The library provides some helper code to assist in defining new constants;
398 the process for defining a constant called `my_constant` goes like this:
399
400 1. [*Define a function that calculates the value of the constant].
401 This should be a template function, and be placed in `boost/math/constants/calculate_constants.hpp`
402 if the constant is to be added to this library,
403 or else defined at the top of your source file if not.
404
405 The function should look like this:
406
407   namespace boost{ namespace math{ namespace constants{ namespace detail{
408
409   template <class Real>
410   template <int N>
411   Real constant_my_constant<Real>::compute(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(mpl::int_<N>))
412   {
413     int required_precision = N ? N : tools::digits<Real>();
414     Real result = /* value computed to required_precision bits */ ;
415     return result;
416   }
417
418   }}}} // namespaces
419
420 Then define a placeholder for the constant itself:
421
422    namespace boost{ namespace math{ namespace constants{
423
424    BOOST_DEFINE_MATH_CONSTANT(my_constant, 0.0, "0");
425
426    }}}
427
428
429 For example, to calculate [pi]/2, add to `boost/math/constants/calculate_constants.hpp`
430
431   template <class T>
432   template<int N>
433   inline T constant_half_pi<T>::compute(BOOST_MATH_EXPLICIT_TEMPLATE_TYPE_SPEC(mpl::int_<N>))
434   {
435      BOOST_MATH_STD_USING
436      return pi<T, policies::policy<policies::digits2<N> > >() / static_cast<T>(2);
437   }
438
439 Then to `boost/math/constants/constants.hpp` add:
440
441    BOOST_DEFINE_MATH_CONSTANT(half_pi, 0.0, "0");  // Actual values are temporary, we'll replace them later.
442
443 [note Previously defined constants like pi and e can be used, but by *not simply calling* `pi<T>()`;
444 specifying the precision via the policy
445 `pi<T, policies::policy<policies::digits2<N> > >()`
446 is essential to ensure full accuracy.]
447
448 [warning Newly defined constants can only be used once they are included in
449 `boost/math/constants/constants.hpp`. So if you add
450 `template <class T, class N> T constant_my_constant{...}`,
451 then you cannot define `constant_my_constant`
452 until you add the temporary `BOOST_DEFINE_MATH_CONSTANT(my_constant, 0.0, "0")`.
453 Failing to do this will result in surprising compile errors:
454 ``
455   error C2143: syntax error : missing ';' before '<'
456   error C2433: 'constant_root_two_div_pi' : 'inline' not permitted on data declarations
457   error C2888: 'T constant_root_two_div_pi' : symbol cannot be defined within namespace 'detail'
458   error C2988: unrecognizable template declaration/definition
459 ``
460 ]
461
462 2. [*You will need an arbitrary precision type to use to calculate the value]. This library
463 currently supports either `cpp_float`, `NTL::RR` or `mpfr_class` used via the bindings in `boost/math/bindings`.
464 The default is to use `NTL::RR` unless you define an alternate macro, for example,
465 `USE_MPFR` or `USE_CPP_FLOAT` at the start of your program.
466
467 3. It is necessary to link to the Boost.Regex library,
468 and probably to your chosen arbitrary precision type library.
469
470 4. You need to add `libs\math\include_private` to your compiler's include path as the needed
471 header is not installed in the usual places by default (this avoids a cyclic dependency between
472 the Math and Multiprecision library's headers).
473
474 5. The complete program to generate the constant `half_pi` using function `calculate_half_pi` is then:
475
476    #define USE_CPP_FLOAT // If required.
477    #include <boost/math/constants/generate.hpp>
478
479    int main()
480    {
481       BOOST_CONSTANTS_GENERATE(half_pi);
482    }
483
484 The output from the program is a snippet of C++ code
485 (actually a macro call) that can be cut and pasted
486 into `boost/math/constants/constants.hpp` or else into your own code, for example:
487
488 [pre
489   BOOST_DEFINE_MATH_CONSTANT(half_pi, 1.570796326794896619231321691639751442e+00, "1.57079632679489661923132169163975144209858469968755291048747229615390820314310449931401741267105853399107404326e+00");
490 ]
491
492 This macro BOOST_DEFINE_MATH_CONSTANT  inserts a C++ struct code snippet that
493 declares the `float`, `double` and `long double` versions of the constant,
494 plus a decimal digit string representation correct to 100 decimal
495 digits, and all the meta-programming machinery needed to select between them.
496
497 The result of an expanded macro for Pi is shown below.
498
499 [import ./pp_pi.hpp]
500
501 [preprocessed_pi]
502
503
504 [endsect] [/section:new_const Defining New Constants]
505
506 [section:constants_faq Math Constants FAQs]
507
508 [h4 Why are ['these] Constants Chosen?]
509 It is, of course, impossible to please everyone with a list like this.
510
511 Some of the criteria we have used are:
512
513 * Used in Boost.Math.
514 * Commonly used.
515 * Expensive to compute.
516 * Requested by users.
517 * [@http://en.wikipedia.org/wiki/Mathematical_constant Used in science and mathematics.]
518 * No integer values (because so cheap to construct).
519
520 (You can easily define your own if found convenient, for example: `FPT one =static_cast<FPT>(42);`).
521
522 [h4 How are constants named?]
523 * Not macros, so no upper case.
524 * All lower case (following C++ standard names).
525 * No CamelCase.
526 * Underscore as _ delimiter between words.
527 * Numbers spelt as words rather than decimal digits (except following pow).
528 * Abbreviation conventions:
529   * root for square root.
530   * cbrt for cube root.
531   * pow for pow function using decimal digits like pow23 for n[super 2/3].
532   * div for divided by or operator /.
533   * minus for operator -, plus for operator +.
534   * sqr for squared.
535   * cubed for cubed n[super 3].
536   * words for greek, like [pi], [zeta] and [Gamma].
537   * words like half, third, three_quarters, sixth for fractions.  (Digit(s) can get muddled).
538   * log10 for log[sub 10]
539   * ln for log[sub e]
540
541 [h4 How are the constants derived?]
542
543 The constants have all been calculated using high-precision software working
544 with up to 300-bit precision giving about 100 decimal digits.
545 (The precision can be arbitrarily chosen and is limited only by compute time).
546
547 [h4 How Accurate are the constants?]
548 The minimum accuracy chosen (100 decimal digits) exceeds the
549 accuracy of reasonably-foreseeable floating-point hardware (256-bit)
550 and should meet most high-precision computations.
551
552 [h4 How are the constants tested?]
553
554 # Comparison using Boost.Test BOOST_CHECK_CLOSE_FRACTION using long double literals,
555 with at least 35 decimal digits, enough to be accurate for all long double implementations.
556 The tolerance is usually twice `long double epsilon`.
557
558 # Comparison with calculation at long double precision.
559 This often requires a slightly higher tolerance than two epsilon
560 because of computational noise from round-off etc,
561 especially when trig and other functions are called.
562
563 # Comparison with independent published values,
564 for example, using [@http://oeis.org/ The On-Line Encyclopedia of Integer Sequences (OEIS)]
565 again using at least 35 decimal digits strings.
566
567 # Comparison with independely calculated values using arbitrary precision tools like
568 [@http://www.wolfram.com/mathematica/ Mathematica], again using at least 35 decimal digits literal strings.
569
570 [warning We have not yet been able to [*check] that
571 [*all] constants are accurate at the full arbitrary precision,
572 at present 100 decimal digits.
573 But certain key values like `e` and `pi` appear to be accurate
574 and internal consistencies suggest that others are this accurate too.
575 ]
576
577 [h4 Why is Portability important?]
578
579 Code written using math constants is easily portable even when using different
580 floating-point types with differing precision.
581
582 It is a mistake to expect that results of computations will be [*identical], but
583 you can achieve the [*best accuracy possible for the floating-point type in use].
584
585 This has no extra cost to the user, but reduces irritating,
586 and often confusing and very hard-to-trace effects,
587 caused by the intrinsically limited precision of floating-point calculations.
588
589 A harmless symptom of this limit is a spurious least-significant digit;
590 at worst, slightly inaccurate constants sometimes cause iterating algorithms
591 to diverge wildly because internal comparisons just fail.
592
593 [h4 What is the Internal Format of the constants, and why?]
594
595 See [link math_toolkit.tutorial tutorial] above for normal use,
596 but this FAQ explains the internal details used for the constants.
597
598 Constants are stored as 100 decimal digit values.
599 However, some compilers do not accept decimal digits strings as long as this.
600 So the constant is split into two parts, with the first containing at least
601 128-bit long double precision (35 decimal digits),
602 and for consistency should be in scientific format with a signed exponent.
603
604 The second part is the value of the constant expressed as a string literal,
605 accurate to at least 100 decimal digits (in practice that means at least 102 digits).
606 Again for consistency use scientific format with a signed exponent.
607
608 For types with precision greater than a long double,
609 then if T is constructible `T `is constructible from a `const char*`
610 then it's directly constructed from the string,
611 otherwise we fall back on lexical_cast to convert to type `T`.
612 (Using a string is necessary because you can't use a numeric constant
613 since even a `long double` might not have enough digits).
614
615 So, for example, a constant like pi is internally defined as
616
617   BOOST_DEFINE_MATH_CONSTANT(pi, 3.141592653589793238462643383279502884e+00, "3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651e+00");
618
619 In this case the significand is 109 decimal digits, ensuring 100 decimal digits are exact, and exponent is zero.
620
621 See [link math_toolkit.new_const defining new constants] to calculate new constants.
622
623 A macro definition like this can be pasted into user code where convenient,
624 or into `boost/math/constants.hpp` if it is to be added to the Boost.Math library.
625
626 [h4 What Floating-point Types could I use?]
627
628 Apart from the built-in floating-point types `float`, `double`, `long double`,
629 there are several arbitrary precision floating-point classes available,
630 but most are not licensed for commercial use.
631
632 [h5  Boost.Multiprecision by Christopher Kormanyos]
633
634 This work is based on an earlier work called e-float:
635 Algorithm 910: A Portable C++ Multiple-Precision System for Special-Function Calculations,
636 in ACM TOMS, {VOL 37, ISSUE 4, (February 2011)} (C) ACM, 2011.
637 [@http://doi.acm.org/10.1145/1916461.1916469]
638 [@https://svn.boost.org/svn/boost/sandbox/e_float/ e_float]
639 but is now re-factored and available under the Boost license in the Boost-sandbox at
640 [@https://svn.boost.org/svn/boost/sandbox/multiprecision/ multiprecision]
641 where it is being refined and prepared for review.
642
643 [h5 Boost.cpp_float by John Maddock using Expression Templates]
644
645 [@https://svn.boost.org/svn/boost/sandbox/big_number/ Big Number]
646 which is a reworking of [@https://svn.boost.org/svn/boost/sandbox/e_float/ e_float]
647 by Christopher Kormanyos to use expression templates for faster execution.
648
649 [h5 NTL class quad_float]
650
651 [@http://shoup.net/ntl/ NTL] by Victor Shoup has fixed and arbitrary high precision fixed and floating-point types.
652 However none of these are licenced for commercial use.
653
654   #include <NTL/quad_float.h> // quad precision 106-bit, about 32 decimal digits.
655   using NTL::to_quad_float; // Less precise than arbitrary precision NTL::RR.
656
657 NTL class `quad_float`, which gives a form of quadruple precision,
658 106-bit significand (but without an extended exponent range.)
659 With an IEC559/IEEE 754 compatible processor,
660 for example Intel X86 family, with 64-bit double, and 53-bit significand,
661 using the significands of [*two] 64-bit doubles,
662 if `std::numeric_limits<double>::digits10` is 16,
663 then we get about twice the precision,
664 so `std::numeric_limits<quad_float>::digits10()` should be 32.
665 (the default `std::numeric_limits<RR>::digits10()` should be about 40).
666 (which seems to agree with experiments).
667 We output constants (including some noisy bits,
668 an approximation to `std::numeric_limits<RR>::max_digits10()`)
669 by adding 2 or 3 extra decimal digits, so using `quad_float::SetOutputPrecision(32 + 3);`
670
671 Apple Mac/Darwin uses a similar ['doubledouble] 106-bit for its built-in `long double` type.
672
673 [note The precision of all `doubledouble` floating-point types is rather odd and values given are only approximate.]
674
675 [*New projects should use __multiprecision.]
676
677 [h5 NTL class RR]
678
679 Arbitrary precision floating point with NTL class RR,
680 default is 150 bit (about 50 decimal digits)
681 used here with 300 bit to output 100 decimal digits,
682 enough for many practical non-'number-theoretic' C++ applications.
683
684 __NTL is [*not licenced for commercial use].
685
686 This class is used in Boost.Math and is an option when using big_number projects to calculate new math constants.
687
688 [*New projects should use __multiprecision.]
689
690 [h5 GMP and MPFR]
691
692 [@http://gmplib.org GMP] and [@http://www.mpfr.org/ MPFR] have also been used to compute constants,
693 but are licensed under the [@http://www.gnu.org/copyleft/lesser.html Lesser GPL license]
694 and are [*not licensed for commercial use].
695
696 [h4 What happened to a previous collection of constants proposed for Boost?]
697
698 A review concluded that the way in which the constants were presented did not meet many peoples needs.
699 None of the methods proposed met many users' essential requirement to allow writing simply `pi` rather than `pi()`.
700 Many science and engineering equations look difficult to read when because function call brackets can be confused
701 with the many other brackets often needed.  All the methods then proposed of avoiding the brackets failed to meet all needs,
702 often on grounds of complexity and lack of applicability to various realistic scenarios.
703
704 So the simple namespace method, proposed on its own, but rejected at the first review,
705 has been added to allow users to have convenient access to float, double and long double values,
706 but combined with template struct and functions to allow simultaneous use
707 with other non-built-in floating-point types.
708
709
710 [h4 Why do the constants (internally) have a struct rather than a simple function?]
711
712 A function mechanism was provided by in previous versions of Boost.Math.
713
714 The new mechanism is to permit partial specialization. See Custom Specializing a constant above.
715 It should also allow use with other packages like [@http://www.ttmath.org/ ttmath Bignum C++ library.]
716
717 [h4 Where can I find other high precision constants?]
718
719 # Constants with very high precision and good accuracy (>40 decimal digits)
720 from Simon Plouffe's web based collection [@http://pi.lacim.uqam.ca/eng/].
721 # [@https://oeis.org/ The On-Line Encyclopedia of Integer Sequences (OEIS)]
722 # Checks using  printed text optically scanned values and converted from:
723 D. E. Knuth, Art of Computer Programming, Appendix A, Table 1, Vol 1, ISBN 0 201 89683 4 (1997)
724 # M. Abrahamovitz & I. E. Stegun, National Bureau of Standards, Handbook of Mathematical Functions,
725 a reference source for formulae now superceded by
726 # Frank W. Olver, Daniel W. Lozier, Ronald F. Boisvert, Charles W. Clark, NIST Handbook of Mathemetical Functions, Cambridge University Press, ISBN 978-0-521-14063-8, 2010.
727 # John F Hart, Computer Approximations, Kreiger (1978) ISBN 0 88275 642 7.
728 # Some values from Cephes Mathematical Library, Stephen L. Moshier
729 and CALC100 100 decimal digit Complex Variable Calculator Program, a DOS utility.
730 # Xavier Gourdon, Pascal Sebah, 50 decimal digits constants at [@http://numbers.computation.free.fr/Constants/constants.html Number, constants and computation].
731
732 [h4 Where are Physical Constants?]
733
734 Not here in this Boost.Math collection, because physical constants:
735
736 * Are measurements, not truely constants.
737 * Are not truly constant and keeping changing as mensuration technology improves.
738 * Have a instrinsic uncertainty.
739 * Mathematical constants are stored and represented at varying precision, but should never be inaccurate.
740
741 Some physical constants may be available in Boost.Units.
742
743 [endsect] [/section:FAQ FAQ]
744
745 [endmathpart] [/section:constants Mathematical Constants]
746
747 [/
748   Copyright 2012 John Maddock and Paul A. Bristow.
749   Distributed under the Boost Software License, Version 1.0.
750   (See accompanying file LICENSE_1_0.txt or copy at
751   http://www.boost.org/LICENSE_1_0.txt).
752 ]
753
754