]> git.donarmstrong.com Git - rsem.git/blob - boost/math/special_functions/binomial.hpp
Updated boost to v1.55.0
[rsem.git] / boost / math / special_functions / binomial.hpp
1 //  Copyright John Maddock 2006.
2 //  Use, modification and distribution are subject to the
3 //  Boost Software License, Version 1.0. (See accompanying file
4 //  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5
6 #ifndef BOOST_MATH_SF_BINOMIAL_HPP
7 #define BOOST_MATH_SF_BINOMIAL_HPP
8
9 #ifdef _MSC_VER
10 #pragma once
11 #endif
12
13 #include <boost/math/special_functions/factorials.hpp>
14 #include <boost/math/special_functions/beta.hpp>
15 #include <boost/math/policies/error_handling.hpp>
16
17 namespace boost{ namespace math{
18
19 template <class T, class Policy>
20 T binomial_coefficient(unsigned n, unsigned k, const Policy& pol)
21 {
22    BOOST_STATIC_ASSERT(!boost::is_integral<T>::value);
23    BOOST_MATH_STD_USING
24    static const char* function = "boost::math::binomial_coefficient<%1%>(unsigned, unsigned)";
25    if(k > n)
26       return policies::raise_domain_error<T>(
27          function, 
28          "The binomial coefficient is undefined for k > n, but got k = %1%.",
29          k, pol);
30    T result;
31    if((k == 0) || (k == n))
32       return 1;
33    if((k == 1) || (k == n-1))
34       return n;
35
36    if(n <= max_factorial<T>::value)
37    {
38       // Use fast table lookup:
39       result = unchecked_factorial<T>(n);
40       result /= unchecked_factorial<T>(n-k);
41       result /= unchecked_factorial<T>(k);
42    }
43    else
44    {
45       // Use the beta function:
46       if(k < n - k)
47          result = k * beta(static_cast<T>(k), static_cast<T>(n-k+1), pol);
48       else
49          result = (n - k) * beta(static_cast<T>(k+1), static_cast<T>(n-k), pol);
50       if(result == 0)
51          return policies::raise_overflow_error<T>(function, 0, pol);
52       result = 1 / result;
53    }
54    // convert to nearest integer:
55    return ceil(result - 0.5f);
56 }
57 //
58 // Type float can only store the first 35 factorials, in order to
59 // increase the chance that we can use a table driven implementation
60 // we'll promote to double:
61 //
62 template <>
63 inline float binomial_coefficient<float, policies::policy<> >(unsigned n, unsigned k, const policies::policy<>& pol)
64 {
65    return policies::checked_narrowing_cast<float, policies::policy<> >(binomial_coefficient<double>(n, k, pol), "boost::math::binomial_coefficient<%1%>(unsigned,unsigned)");
66 }
67
68 template <class T>
69 inline T binomial_coefficient(unsigned n, unsigned k)
70 {
71    return binomial_coefficient<T>(n, k, policies::policy<>());
72 }
73
74 } // namespace math
75 } // namespace boost
76
77
78 #endif // BOOST_MATH_SF_BINOMIAL_HPP
79
80
81