1 // (C) 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)
6 #ifndef BOOST_MATH_SPECIAL_BETA_HPP
7 #define BOOST_MATH_SPECIAL_BETA_HPP
13 #include <boost/math/special_functions/math_fwd.hpp>
14 #include <boost/math/tools/config.hpp>
15 #include <boost/math/special_functions/gamma.hpp>
16 #include <boost/math/special_functions/binomial.hpp>
17 #include <boost/math/special_functions/factorials.hpp>
18 #include <boost/math/special_functions/erf.hpp>
19 #include <boost/math/special_functions/log1p.hpp>
20 #include <boost/math/special_functions/expm1.hpp>
21 #include <boost/math/special_functions/trunc.hpp>
22 #include <boost/math/tools/roots.hpp>
23 #include <boost/static_assert.hpp>
24 #include <boost/config/no_tr1/cmath.hpp>
26 namespace boost{ namespace math{
31 // Implementation of Beta(a,b) using the Lanczos approximation:
33 template <class T, class Lanczos, class Policy>
34 T beta_imp(T a, T b, const Lanczos&, const Policy& pol)
36 BOOST_MATH_STD_USING // for ADL of std names
39 return policies::raise_domain_error<T>("boost::math::beta<%1%>(%1%,%1%)", "The arguments to the beta function must be greater than zero (got a=%1%).", a, pol);
41 return policies::raise_domain_error<T>("boost::math::beta<%1%>(%1%,%1%)", "The arguments to the beta function must be greater than zero (got b=%1%).", b, pol);
49 if((c == a) && (b < tools::epsilon<T>()))
51 else if((c == b) && (a < tools::epsilon<T>()))
57 else if(c < tools::epsilon<T>())
66 // This code appears to be no longer necessary: it was
67 // used to offset errors introduced from the Lanczos
68 // approximation, but the current Lanczos approximations
69 // are sufficiently accurate for all z that we can ditch
70 // this. It remains in the file for future reference...
72 // If a or b are less than 1, shift to greater than 1:
90 // Lanczos calculation:
91 T agh = static_cast<T>(a + Lanczos::g() - 0.5f);
92 T bgh = static_cast<T>(b + Lanczos::g() - 0.5f);
93 T cgh = static_cast<T>(c + Lanczos::g() - 0.5f);
94 result = Lanczos::lanczos_sum_expG_scaled(a) * (Lanczos::lanczos_sum_expG_scaled(b) / Lanczos::lanczos_sum_expG_scaled(c));
95 T ambh = a - 0.5f - b;
96 if((fabs(b * ambh) < (cgh * 100)) && (a > 100))
98 // Special case where the base of the power term is close to 1
99 // compute (1+x)^y instead:
100 result *= exp(ambh * boost::math::log1p(-b / cgh, pol));
104 result *= pow(agh / cgh, a - T(0.5) - b);
107 // this avoids possible overflow, but appears to be marginally less accurate:
108 result *= pow((agh / cgh) * (bgh / cgh), b);
110 result *= pow((agh * bgh) / (cgh * cgh), b);
111 result *= sqrt(boost::math::constants::e<T>() / bgh);
113 // If a and b were originally less than 1 we need to scale the result:
117 } // template <class T, class Lanczos> beta_imp(T a, T b, const Lanczos&)
120 // Generic implementation of Beta(a,b) without Lanczos approximation support
121 // (Caution this is slow!!!):
123 template <class T, class Policy>
124 T beta_imp(T a, T b, const lanczos::undefined_lanczos& l, const Policy& pol)
129 return policies::raise_domain_error<T>("boost::math::beta<%1%>(%1%,%1%)", "The arguments to the beta function must be greater than zero (got a=%1%).", a, pol);
131 return policies::raise_domain_error<T>("boost::math::beta<%1%>(%1%,%1%)", "The arguments to the beta function must be greater than zero (got b=%1%).", b, pol);
136 if ((c == a) && (b < tools::epsilon<T>()))
138 else if ((c == b) && (a < tools::epsilon<T>()))
144 else if (c < tools::epsilon<T>())
151 // Regular cases start here:
152 const T min_sterling = minimum_argument_for_bernoulli_recursion<T>();
158 shift_a = 1 + ltrunc(min_sterling - a);
160 shift_b = 1 + ltrunc(min_sterling - b);
161 long shift_c = shift_a + shift_b;
163 if ((shift_a == 0) && (shift_b == 0))
165 return pow(a / c, a) * pow(b / c, b) * scaled_tgamma_no_lanczos(a, pol) * scaled_tgamma_no_lanczos(b, pol) / scaled_tgamma_no_lanczos(c, pol);
167 else if ((a < 1) && (b < 1))
169 return boost::math::tgamma(a, pol) * (boost::math::tgamma(b, pol) / boost::math::tgamma(c));
172 return boost::math::tgamma(a, pol) * boost::math::tgamma_delta_ratio(b, a, pol);
174 return boost::math::tgamma(b, pol) * boost::math::tgamma_delta_ratio(a, b, pol);
177 T result = beta_imp(T(a + shift_a), T(b + shift_b), l, pol);
181 for (long i = 0; i < shift_c; ++i)
192 } // template <class T>T beta_imp(T a, T b, const lanczos::undefined_lanczos& l)
196 // Compute the leading power terms in the incomplete Beta:
198 // (x^a)(y^b)/Beta(a,b) when normalised, and
199 // (x^a)(y^b) otherwise.
201 // Almost all of the error in the incomplete beta comes from this
202 // function: particularly when a and b are large. Computing large
203 // powers are *hard* though, and using logarithms just leads to
204 // horrendous cancellation errors.
206 template <class T, class Lanczos, class Policy>
207 T ibeta_power_terms(T a,
215 const char* function = "boost::math::ibeta<%1%>(%1%, %1%, %1%)")
221 // can we do better here?
222 return pow(x, a) * pow(y, b);
229 // combine power terms with Lanczos approximation:
230 T agh = static_cast<T>(a + Lanczos::g() - 0.5f);
231 T bgh = static_cast<T>(b + Lanczos::g() - 0.5f);
232 T cgh = static_cast<T>(c + Lanczos::g() - 0.5f);
233 result = Lanczos::lanczos_sum_expG_scaled(c) / (Lanczos::lanczos_sum_expG_scaled(a) * Lanczos::lanczos_sum_expG_scaled(b));
235 // combine with the leftover terms from the Lanczos approximation:
236 result *= sqrt(bgh / boost::math::constants::e<T>());
237 result *= sqrt(agh / cgh);
239 // l1 and l2 are the base of the exponents minus one:
240 T l1 = (x * b - y * agh) / agh;
241 T l2 = (y * a - x * bgh) / bgh;
242 if(((std::min)(fabs(l1), fabs(l2)) < 0.2))
244 // when the base of the exponent is very near 1 we get really
245 // gross errors unless extra care is taken:
246 if((l1 * l2 > 0) || ((std::min)(a, b) < 1))
249 // This first branch handles the simple cases where either:
251 // * The two power terms both go in the same direction
252 // (towards zero or towards infinity). In this case if either
253 // term overflows or underflows, then the product of the two must
255 // *Alternatively if one exponent is less than one, then we
256 // can't productively use it to eliminate overflow or underflow
257 // from the other term. Problems with spurious overflow/underflow
258 // can't be ruled out in this case, but it is *very* unlikely
259 // since one of the power terms will evaluate to a number close to 1.
263 result *= exp(a * boost::math::log1p(l1, pol));
264 BOOST_MATH_INSTRUMENT_VARIABLE(result);
268 result *= pow((x * cgh) / agh, a);
269 BOOST_MATH_INSTRUMENT_VARIABLE(result);
273 result *= exp(b * boost::math::log1p(l2, pol));
274 BOOST_MATH_INSTRUMENT_VARIABLE(result);
278 result *= pow((y * cgh) / bgh, b);
279 BOOST_MATH_INSTRUMENT_VARIABLE(result);
282 else if((std::max)(fabs(l1), fabs(l2)) < 0.5)
285 // Both exponents are near one and both the exponents are
286 // greater than one and further these two
287 // power terms tend in opposite directions (one towards zero,
288 // the other towards infinity), so we have to combine the terms
289 // to avoid any risk of overflow or underflow.
291 // We do this by moving one power term inside the other, we have:
293 // (1 + l1)^a * (1 + l2)^b
294 // = ((1 + l1)*(1 + l2)^(b/a))^a
295 // = (1 + l1 + l3 + l1*l3)^a ; l3 = (1 + l2)^(b/a) - 1
296 // = exp((b/a) * log(1 + l2)) - 1
298 // The tricky bit is deciding which term to move inside :-)
299 // By preference we move the larger term inside, so that the
300 // size of the largest exponent is reduced. However, that can
301 // only be done as long as l3 (see above) is also small.
303 bool small_a = a < b;
305 if((small_a && (ratio * l2 < 0.1)) || (!small_a && (l1 / ratio > 0.1)))
307 T l3 = boost::math::expm1(ratio * boost::math::log1p(l2, pol), pol);
308 l3 = l1 + l3 + l3 * l1;
309 l3 = a * boost::math::log1p(l3, pol);
311 BOOST_MATH_INSTRUMENT_VARIABLE(result);
315 T l3 = boost::math::expm1(boost::math::log1p(l1, pol) / ratio, pol);
316 l3 = l2 + l3 + l3 * l2;
317 l3 = b * boost::math::log1p(l3, pol);
319 BOOST_MATH_INSTRUMENT_VARIABLE(result);
322 else if(fabs(l1) < fabs(l2))
324 // First base near 1 only:
325 T l = a * boost::math::log1p(l1, pol)
326 + b * log((y * cgh) / bgh);
327 if((l <= tools::log_min_value<T>()) || (l >= tools::log_max_value<T>()))
330 if(l >= tools::log_max_value<T>())
331 return policies::raise_overflow_error<T>(function, 0, pol);
336 BOOST_MATH_INSTRUMENT_VARIABLE(result);
340 // Second base near 1 only:
341 T l = b * boost::math::log1p(l2, pol)
342 + a * log((x * cgh) / agh);
343 if((l <= tools::log_min_value<T>()) || (l >= tools::log_max_value<T>()))
346 if(l >= tools::log_max_value<T>())
347 return policies::raise_overflow_error<T>(function, 0, pol);
352 BOOST_MATH_INSTRUMENT_VARIABLE(result);
358 T b1 = (x * cgh) / agh;
359 T b2 = (y * cgh) / bgh;
362 BOOST_MATH_INSTRUMENT_VARIABLE(b1);
363 BOOST_MATH_INSTRUMENT_VARIABLE(b2);
364 BOOST_MATH_INSTRUMENT_VARIABLE(l1);
365 BOOST_MATH_INSTRUMENT_VARIABLE(l2);
366 if((l1 >= tools::log_max_value<T>())
367 || (l1 <= tools::log_min_value<T>())
368 || (l2 >= tools::log_max_value<T>())
369 || (l2 <= tools::log_min_value<T>())
372 // Oops, under/overflow, sidestep if we can:
375 T p1 = pow(b2, b / a);
376 T l3 = a * (log(b1) + log(p1));
377 if((l3 < tools::log_max_value<T>())
378 && (l3 > tools::log_min_value<T>()))
380 result *= pow(p1 * b1, a);
384 l2 += l1 + log(result);
385 if(l2 >= tools::log_max_value<T>())
386 return policies::raise_overflow_error<T>(function, 0, pol);
392 T p1 = pow(b1, a / b);
393 T l3 = (log(p1) + log(b2)) * b;
394 if((l3 < tools::log_max_value<T>())
395 && (l3 > tools::log_min_value<T>()))
397 result *= pow(p1 * b2, b);
401 l2 += l1 + log(result);
402 if(l2 >= tools::log_max_value<T>())
403 return policies::raise_overflow_error<T>(function, 0, pol);
407 BOOST_MATH_INSTRUMENT_VARIABLE(result);
411 // finally the normal case:
412 result *= pow(b1, a) * pow(b2, b);
413 BOOST_MATH_INSTRUMENT_VARIABLE(result);
417 BOOST_MATH_INSTRUMENT_VARIABLE(result);
422 // Compute the leading power terms in the incomplete Beta:
424 // (x^a)(y^b)/Beta(a,b) when normalised, and
425 // (x^a)(y^b) otherwise.
427 // Almost all of the error in the incomplete beta comes from this
428 // function: particularly when a and b are large. Computing large
429 // powers are *hard* though, and using logarithms just leads to
430 // horrendous cancellation errors.
432 // This version is generic, slow, and does not use the Lanczos approximation.
434 template <class T, class Policy>
435 T ibeta_power_terms(T a,
439 const boost::math::lanczos::undefined_lanczos& l,
443 const char* = "boost::math::ibeta<%1%>(%1%, %1%, %1%)")
449 return prefix * pow(x, a) * pow(y, b);
454 const T min_sterling = minimum_argument_for_bernoulli_recursion<T>();
459 if (a < min_sterling)
460 shift_a = 1 + ltrunc(min_sterling - a);
461 if (b < min_sterling)
462 shift_b = 1 + ltrunc(min_sterling - b);
464 if ((shift_a == 0) && (shift_b == 0))
469 power1 = pow((x * y * c * c) / (a * b), a);
470 power2 = pow((y * c) / b, b - a);
474 power1 = pow((x * y * c * c) / (a * b), b);
475 power2 = pow((x * c) / a, a - b);
477 if (!(boost::math::isnormal)(power1) || !(boost::math::isnormal)(power2))
479 // We have to use logs :(
480 return prefix * exp(a * log(x * c / a) + b * log(y * c / b)) * scaled_tgamma_no_lanczos(c, pol) / (scaled_tgamma_no_lanczos(a, pol) * scaled_tgamma_no_lanczos(b, pol));
482 return prefix * power1 * power2 * scaled_tgamma_no_lanczos(c, pol) / (scaled_tgamma_no_lanczos(a, pol) * scaled_tgamma_no_lanczos(b, pol));
485 T power1 = pow(x, a);
486 T power2 = pow(y, b);
487 T bet = beta_imp(a, b, l, pol);
489 if(!(boost::math::isnormal)(power1) || !(boost::math::isnormal)(power2) || !(boost::math::isnormal)(bet))
491 int shift_c = shift_a + shift_b;
492 T result = ibeta_power_terms(T(a + shift_a), T(b + shift_b), x, y, l, normalised, pol, prefix);
493 if ((boost::math::isnormal)(result))
495 for (int i = 0; i < shift_c; ++i)
509 return prefix * result;
513 T log_result = log(x) * a + log(y) * b + log(prefix);
514 if ((boost::math::isnormal)(bet))
515 log_result -= log(bet);
517 log_result += boost::math::lgamma(c, pol) - boost::math::lgamma(a) - boost::math::lgamma(c, pol);
518 return exp(log_result);
521 return prefix * power1 * (power2 / bet);
524 // Series approximation to the incomplete beta:
527 struct ibeta_series_t
529 typedef T result_type;
530 ibeta_series_t(T a_, T b_, T x_, T mult) : result(mult), x(x_), apn(a_), poch(1-b_), n(1) {}
535 result *= poch * x / n;
541 T result, x, apn, poch;
545 template <class T, class Lanczos, class Policy>
546 T ibeta_series(T a, T b, T x, T s0, const Lanczos&, bool normalised, T* p_derivative, T y, const Policy& pol)
552 BOOST_ASSERT((p_derivative == 0) || normalised);
558 // incomplete beta power term, combined with the Lanczos approximation:
559 T agh = static_cast<T>(a + Lanczos::g() - 0.5f);
560 T bgh = static_cast<T>(b + Lanczos::g() - 0.5f);
561 T cgh = static_cast<T>(c + Lanczos::g() - 0.5f);
562 result = Lanczos::lanczos_sum_expG_scaled(c) / (Lanczos::lanczos_sum_expG_scaled(a) * Lanczos::lanczos_sum_expG_scaled(b));
564 T l1 = log(cgh / bgh) * (b - 0.5f);
565 T l2 = log(x * cgh / agh) * a;
567 // Check for over/underflow in the power terms:
569 if((l1 > tools::log_min_value<T>())
570 && (l1 < tools::log_max_value<T>())
571 && (l2 > tools::log_min_value<T>())
572 && (l2 < tools::log_max_value<T>()))
575 result *= exp((b - 0.5f) * boost::math::log1p(a / bgh, pol));
577 result *= pow(cgh / bgh, b - 0.5f);
578 result *= pow(x * cgh / agh, a);
579 result *= sqrt(agh / boost::math::constants::e<T>());
583 *p_derivative = result * pow(y, b);
584 BOOST_ASSERT(*p_derivative >= 0);
590 // Oh dear, we need logs, and this *will* cancel:
592 result = log(result) + l1 + l2 + (log(agh) - 1) / 2;
594 *p_derivative = exp(result + b * log(y));
595 result = exp(result);
600 // Non-normalised, just compute the power:
603 if(result < tools::min_value<T>())
604 return s0; // Safeguard: series can't cope with denorms.
605 ibeta_series_t<T> s(a, b, x, result);
606 boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
607 result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, s0);
608 policies::check_series_iterations<T>("boost::math::ibeta<%1%>(%1%, %1%, %1%) in ibeta_series (with lanczos)", max_iter, pol);
612 // Incomplete Beta series again, this time without Lanczos support:
614 template <class T, class Policy>
615 T ibeta_series(T a, T b, T x, T s0, const boost::math::lanczos::undefined_lanczos& l, bool normalised, T* p_derivative, T y, const Policy& pol)
620 BOOST_ASSERT((p_derivative == 0) || normalised);
624 const T min_sterling = minimum_argument_for_bernoulli_recursion<T>();
629 if (a < min_sterling)
630 shift_a = 1 + ltrunc(min_sterling - a);
631 if (b < min_sterling)
632 shift_b = 1 + ltrunc(min_sterling - b);
636 if ((shift_a == 0) && (shift_b == 0))
638 result = pow(x * c / a, a) * pow(c / b, b) * scaled_tgamma_no_lanczos(c, pol) / (scaled_tgamma_no_lanczos(a, pol) * scaled_tgamma_no_lanczos(b, pol));
640 else if ((a < 1) && (b > 1))
641 result = pow(x, a) / (boost::math::tgamma(a, pol) * boost::math::tgamma_delta_ratio(b, a, pol));
645 T bet = beta_imp(a, b, l, pol);
646 if (!(boost::math::isnormal)(power) || !(boost::math::isnormal)(bet))
648 result = exp(a * log(x) + boost::math::lgamma(c, pol) - boost::math::lgamma(a, pol) - boost::math::lgamma(b, pol));
651 result = power / bet;
655 *p_derivative = result * pow(y, b);
656 BOOST_ASSERT(*p_derivative >= 0);
661 // Non-normalised, just compute the power:
664 if(result < tools::min_value<T>())
665 return s0; // Safeguard: series can't cope with denorms.
666 ibeta_series_t<T> s(a, b, x, result);
667 boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
668 result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, s0);
669 policies::check_series_iterations<T>("boost::math::ibeta<%1%>(%1%, %1%, %1%) in ibeta_series (without lanczos)", max_iter, pol);
674 // Continued fraction for the incomplete beta:
677 struct ibeta_fraction2_t
679 typedef std::pair<T, T> result_type;
681 ibeta_fraction2_t(T a_, T b_, T x_, T y_) : a(a_), b(b_), x(x_), y(y_), m(0) {}
683 result_type operator()()
685 T aN = (a + m - 1) * (a + b + m - 1) * m * (b - m) * x * x;
686 T denom = (a + 2 * m - 1);
689 T bN = static_cast<T>(m);
690 bN += (m * (b - m) * x) / (a + 2*m - 1);
691 bN += ((a + m) * (a * y - b * x + 1 + m *(2 - x))) / (a + 2*m + 1);
695 return std::make_pair(aN, bN);
703 // Evaluate the incomplete beta via the continued fraction representation:
705 template <class T, class Policy>
706 inline T ibeta_fraction2(T a, T b, T x, T y, const Policy& pol, bool normalised, T* p_derivative)
708 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
710 T result = ibeta_power_terms(a, b, x, y, lanczos_type(), normalised, pol);
713 *p_derivative = result;
714 BOOST_ASSERT(*p_derivative >= 0);
719 ibeta_fraction2_t<T> f(a, b, x, y);
720 T fract = boost::math::tools::continued_fraction_b(f, boost::math::policies::get_epsilon<T, Policy>());
721 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
722 BOOST_MATH_INSTRUMENT_VARIABLE(result);
723 return result / fract;
726 // Computes the difference between ibeta(a,b,x) and ibeta(a+k,b,x):
728 template <class T, class Policy>
729 T ibeta_a_step(T a, T b, T x, T y, int k, const Policy& pol, bool normalised, T* p_derivative)
731 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
733 BOOST_MATH_INSTRUMENT_VARIABLE(k);
735 T prefix = ibeta_power_terms(a, b, x, y, lanczos_type(), normalised, pol);
738 *p_derivative = prefix;
739 BOOST_ASSERT(*p_derivative >= 0);
746 // series summation from 0 to k-1:
747 for(int i = 0; i < k-1; ++i)
749 term *= (a+b+i) * x / (a+i+1);
757 // This function is only needed for the non-regular incomplete beta,
758 // it computes the delta in:
759 // beta(a,b,x) = prefix + delta * beta(a+k,b,x)
760 // it is currently only called for small k.
763 inline T rising_factorial_ratio(T a, T b, int k)
766 // (a)(a+1)(a+2)...(a+k-1)
767 // _______________________
768 // (b)(b+1)(b+2)...(b+k-1)
770 // This is only called with small k, for large k
771 // it is grossly inefficient, do not use outside it's
772 // intended purpose!!!
773 BOOST_MATH_INSTRUMENT_VARIABLE(k);
777 for(int i = 0; i < k; ++i)
778 result *= (a+i) / (b+i);
782 // Routine for a > 15, b < 1
784 // Begin by figuring out how large our table of Pn's should be,
785 // quoted accuracies are "guestimates" based on empiracal observation.
786 // Note that the table size should never exceed the size of our
787 // tables of factorials.
792 // This is likely to be enough for ~35-50 digit accuracy
793 // but it's hard to quantify exactly:
794 BOOST_STATIC_CONSTANT(unsigned, value =
795 ::boost::math::max_factorial<T>::value >= 100 ? 50
796 : ::boost::math::max_factorial<T>::value >= ::boost::math::max_factorial<double>::value ? 30
797 : ::boost::math::max_factorial<T>::value >= ::boost::math::max_factorial<float>::value ? 15 : 1);
798 BOOST_STATIC_ASSERT(::boost::math::max_factorial<T>::value >= ::boost::math::max_factorial<float>::value);
801 struct Pn_size<float>
803 BOOST_STATIC_CONSTANT(unsigned, value = 15); // ~8-15 digit accuracy
804 BOOST_STATIC_ASSERT(::boost::math::max_factorial<float>::value >= 30);
807 struct Pn_size<double>
809 BOOST_STATIC_CONSTANT(unsigned, value = 30); // 16-20 digit accuracy
810 BOOST_STATIC_ASSERT(::boost::math::max_factorial<double>::value >= 60);
813 struct Pn_size<long double>
815 BOOST_STATIC_CONSTANT(unsigned, value = 50); // ~35-50 digit accuracy
816 BOOST_STATIC_ASSERT(::boost::math::max_factorial<long double>::value >= 100);
819 template <class T, class Policy>
820 T beta_small_b_large_a_series(T a, T b, T x, T y, T s0, T mult, const Policy& pol, bool normalised)
822 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
825 // This is DiDonato and Morris's BGRAT routine, see Eq's 9 through 9.6.
827 // Some values we'll need later, these are Eq 9.1:
833 lx = boost::math::log1p(-y, pol);
837 // and from from 9.2:
839 T h = regularised_gamma_prefix(b, u, pol, lanczos_type());
840 if(h <= tools::min_value<T>())
844 prefix = h / boost::math::tgamma_delta_ratio(a, b, pol);
849 prefix = full_igamma_prefix(b, u, pol) / pow(t, b);
853 // now we need the quantity Pn, unfortunatately this is computed
854 // recursively, and requires a full history of all the previous values
855 // so no choice but to declare a big table and hope it's big enough...
857 T p[ ::boost::math::detail::Pn_size<T>::value ] = { 1 }; // see 9.3.
859 // Now an initial value for J, see 9.6:
861 T j = boost::math::gamma_q(b, u, pol) / h;
863 // Now we can start to pull things together and evaluate the sum in Eq 9:
865 T sum = s0 + prefix * j; // Value at N = 0
866 // some variables we'll need:
867 unsigned tnp1 = 1; // 2*N+1
874 for(unsigned n = 1; n < sizeof(p)/sizeof(p[0]); ++n)
877 // debugging code, enable this if you want to determine whether
878 // the table of Pn's is large enough...
880 static int max_count = 2;
884 std::cerr << "Max iterations in BGRAT was " << n << std::endl;
888 // begin by evaluating the next Pn from Eq 9.4:
894 for(unsigned m = 1; m < n; ++m)
897 p[n] += mbn * p[n-m] / boost::math::unchecked_factorial<T>(tmp1);
901 p[n] += bm1 / boost::math::unchecked_factorial<T>(tnp1);
903 // Now we want Jn from Jn-1 using Eq 9.6:
905 j = (b2n * (b2n + 1) * j + (u + b2n + 1) * lxp) / t4;
909 // pull it together with Eq 9:
911 T r = prefix * p[n] * j;
915 if(fabs(r) < fabs(tools::epsilon<T>() * sum))
920 if(fabs(r / tools::epsilon<T>()) < fabs(sum))
925 } // template <class T, class Lanczos>T beta_small_b_large_a_series(T a, T b, T x, T y, T s0, T mult, const Lanczos& l, bool normalised)
928 // For integer arguments we can relate the incomplete beta to the
929 // complement of the binomial distribution cdf and use this finite sum.
932 T binomial_ccdf(T n, T k, T x, T y)
934 BOOST_MATH_STD_USING // ADL of std names
936 T result = pow(x, n);
938 if(result > tools::min_value<T>())
941 for(unsigned i = itrunc(T(n - 1)); i > k; --i)
943 term *= ((i + 1) * y) / ((n - i) * x);
949 // First term underflows so we need to start at the mode of the
950 // distribution and work outwards:
951 int start = itrunc(n * x);
953 start = itrunc(k + 2);
954 result = pow(x, start) * pow(y, n - start) * boost::math::binomial_coefficient<T>(itrunc(n), itrunc(start));
957 // OK, starting slightly above the mode didn't work,
958 // we'll have to sum the terms the old fashioned way:
959 for(unsigned i = start - 1; i > k; --i)
961 result += pow(x, (int)i) * pow(y, n - i) * boost::math::binomial_coefficient<T>(itrunc(n), itrunc(i));
967 T start_term = result;
968 for(unsigned i = start - 1; i > k; --i)
970 term *= ((i + 1) * y) / ((n - i) * x);
974 for(unsigned i = start + 1; i <= n; ++i)
976 term *= (n - i + 1) * x / (i * y);
987 // The incomplete beta function implementation:
988 // This is just a big bunch of spagetti code to divide up the
989 // input range and select the right implementation method for
992 template <class T, class Policy>
993 T ibeta_imp(T a, T b, T x, const Policy& pol, bool inv, bool normalised, T* p_derivative)
995 static const char* function = "boost::math::ibeta<%1%>(%1%, %1%, %1%)";
996 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
997 BOOST_MATH_STD_USING // for ADL of std math functions.
999 BOOST_MATH_INSTRUMENT_VARIABLE(a);
1000 BOOST_MATH_INSTRUMENT_VARIABLE(b);
1001 BOOST_MATH_INSTRUMENT_VARIABLE(x);
1002 BOOST_MATH_INSTRUMENT_VARIABLE(inv);
1003 BOOST_MATH_INSTRUMENT_VARIABLE(normalised);
1009 BOOST_ASSERT((p_derivative == 0) || normalised);
1012 *p_derivative = -1; // value not set.
1014 if((x < 0) || (x > 1))
1015 return policies::raise_domain_error<T>(function, "Parameter x outside the range [0,1] in the incomplete beta function (got x=%1%).", x, pol);
1020 return policies::raise_domain_error<T>(function, "The argument a to the incomplete beta function must be >= zero (got a=%1%).", a, pol);
1022 return policies::raise_domain_error<T>(function, "The argument b to the incomplete beta function must be >= zero (got b=%1%).", b, pol);
1023 // extend to a few very special cases:
1027 return policies::raise_domain_error<T>(function, "The arguments a and b to the incomplete beta function cannot both be zero, with x=%1%.", x, pol);
1029 return static_cast<T>(inv ? 0 : 1);
1034 return static_cast<T>(inv ? 1 : 0);
1040 return policies::raise_domain_error<T>(function, "The argument a to the incomplete beta function must be greater than zero (got a=%1%).", a, pol);
1042 return policies::raise_domain_error<T>(function, "The argument b to the incomplete beta function must be greater than zero (got b=%1%).", b, pol);
1049 *p_derivative = (a == 1) ? (T)1 : (a < 1) ? T(tools::max_value<T>() / 2) : T(tools::min_value<T>() * 2);
1051 return (invert ? (normalised ? T(1) : boost::math::beta(a, b, pol)) : T(0));
1057 *p_derivative = (b == 1) ? T(1) : (b < 1) ? T(tools::max_value<T>() / 2) : T(tools::min_value<T>() * 2);
1059 return (invert == 0 ? (normalised ? 1 : boost::math::beta(a, b, pol)) : 0);
1061 if((a == 0.5f) && (b == 0.5f))
1063 // We have an arcsine distribution:
1066 *p_derivative = 1 / constants::pi<T>() * sqrt(y * x);
1068 T p = invert ? asin(sqrt(y)) / constants::half_pi<T>() : asin(sqrt(x)) / constants::half_pi<T>();
1070 p *= constants::pi<T>();
1082 // Special case see: http://functions.wolfram.com/GammaBetaErf/BetaRegularized/03/01/01/
1088 return invert ? y : x;
1093 *p_derivative = a * pow(x, a - 1);
1097 p = invert ? T(-boost::math::expm1(a * boost::math::log1p(-y, pol), pol)) : T(exp(a * boost::math::log1p(-y, pol)));
1099 p = invert ? T(-boost::math::powm1(x, a, pol)) : T(pow(x, a));
1105 if((std::min)(a, b) <= 1)
1112 BOOST_MATH_INSTRUMENT_VARIABLE(invert);
1114 if((std::max)(a, b) <= 1)
1117 if((a >= (std::min)(T(0.2), b)) || (pow(x, a) <= 0.9))
1121 fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);
1122 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1126 fract = -(normalised ? 1 : boost::math::beta(a, b, pol));
1128 fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);
1129 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1141 fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);
1142 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1146 fract = -(normalised ? 1 : boost::math::beta(a, b, pol));
1148 fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);
1149 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1154 // Sidestep on a, and then use the series representation:
1158 prefix = rising_factorial_ratio(T(a+b), a, 20);
1164 fract = ibeta_a_step(a, b, x, y, 20, pol, normalised, p_derivative);
1167 fract = beta_small_b_large_a_series(T(a + 20), b, x, y, fract, prefix, pol, normalised);
1168 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1172 fract -= (normalised ? 1 : boost::math::beta(a, b, pol));
1174 fract = -beta_small_b_large_a_series(T(a + 20), b, x, y, fract, prefix, pol, normalised);
1175 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1182 // One of a, b < 1 only:
1183 if((b <= 1) || ((x < 0.1) && (pow(b * x, a) <= 0.7)))
1187 fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);
1188 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1192 fract = -(normalised ? 1 : boost::math::beta(a, b, pol));
1194 fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);
1195 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1208 fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);
1209 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1213 fract = -(normalised ? 1 : boost::math::beta(a, b, pol));
1215 fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);
1216 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1223 fract = beta_small_b_large_a_series(a, b, x, y, T(0), T(1), pol, normalised);
1224 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1228 fract = -(normalised ? 1 : boost::math::beta(a, b, pol));
1230 fract = -beta_small_b_large_a_series(a, b, x, y, fract, T(1), pol, normalised);
1231 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1236 // Sidestep to improve errors:
1240 prefix = rising_factorial_ratio(T(a+b), a, 20);
1246 fract = ibeta_a_step(a, b, x, y, 20, pol, normalised, p_derivative);
1247 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1250 fract = beta_small_b_large_a_series(T(a + 20), b, x, y, fract, prefix, pol, normalised);
1251 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1255 fract -= (normalised ? 1 : boost::math::beta(a, b, pol));
1257 fract = -beta_small_b_large_a_series(T(a + 20), b, x, y, fract, prefix, pol, normalised);
1258 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1270 lambda = a - (a + b) * x;
1274 lambda = (a + b) * y - b;
1281 BOOST_MATH_INSTRUMENT_VARIABLE(invert);
1286 if((floor(a) == a) && (floor(b) == b) && (a < (std::numeric_limits<int>::max)() - 100) && (y != 1))
1288 // relate to the binomial distribution and use a finite sum:
1291 fract = binomial_ccdf(n, k, x, y);
1293 fract *= boost::math::beta(a, b, pol);
1294 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1296 else if(b * x <= 0.7)
1300 fract = ibeta_series(a, b, x, T(0), lanczos_type(), normalised, p_derivative, y, pol);
1301 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1305 fract = -(normalised ? 1 : boost::math::beta(a, b, pol));
1307 fract = -ibeta_series(a, b, x, fract, lanczos_type(), normalised, p_derivative, y, pol);
1308 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1313 // sidestep so we can use the series representation:
1314 int n = itrunc(T(floor(b)), pol);
1321 prefix = rising_factorial_ratio(T(a+bbar), bbar, n);
1327 fract = ibeta_a_step(bbar, a, y, x, n, pol, normalised, static_cast<T*>(0));
1328 fract = beta_small_b_large_a_series(a, bbar, x, y, fract, T(1), pol, normalised);
1330 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1334 // The formula here for the non-normalised case is tricky to figure
1335 // out (for me!!), and requires two pochhammer calculations rather
1336 // than one, so leave it for now and only use this in the normalized case....
1337 int n = itrunc(T(floor(b)), pol);
1344 fract = ibeta_a_step(bbar, a, y, x, n, pol, normalised, static_cast<T*>(0));
1345 fract += ibeta_a_step(a, bbar, x, y, 20, pol, normalised, static_cast<T*>(0));
1347 fract -= 1; // Note this line would need changing if we ever enable this branch in non-normalized case
1348 fract = beta_small_b_large_a_series(T(a+20), bbar, x, y, fract, T(1), pol, normalised);
1354 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1358 fract = ibeta_fraction2(a, b, x, y, pol, normalised, p_derivative);
1359 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1364 fract = ibeta_fraction2(a, b, x, y, pol, normalised, p_derivative);
1365 BOOST_MATH_INSTRUMENT_VARIABLE(fract);
1370 if(*p_derivative < 0)
1372 *p_derivative = ibeta_power_terms(a, b, x, y, lanczos_type(), true, pol);
1376 if(*p_derivative != 0)
1378 if((tools::max_value<T>() * div < *p_derivative))
1380 // overflow, return an arbitarily large value:
1381 *p_derivative = tools::max_value<T>() / 2;
1385 *p_derivative /= div;
1389 return invert ? (normalised ? 1 : boost::math::beta(a, b, pol)) - fract : fract;
1390 } // template <class T, class Lanczos>T ibeta_imp(T a, T b, T x, const Lanczos& l, bool inv, bool normalised)
1392 template <class T, class Policy>
1393 inline T ibeta_imp(T a, T b, T x, const Policy& pol, bool inv, bool normalised)
1395 return ibeta_imp(a, b, x, pol, inv, normalised, static_cast<T*>(0));
1398 template <class T, class Policy>
1399 T ibeta_derivative_imp(T a, T b, T x, const Policy& pol)
1401 static const char* function = "ibeta_derivative<%1%>(%1%,%1%,%1%)";
1403 // start with the usual error checks:
1406 return policies::raise_domain_error<T>(function, "The argument a to the incomplete beta function must be greater than zero (got a=%1%).", a, pol);
1408 return policies::raise_domain_error<T>(function, "The argument b to the incomplete beta function must be greater than zero (got b=%1%).", b, pol);
1409 if((x < 0) || (x > 1))
1410 return policies::raise_domain_error<T>(function, "Parameter x outside the range [0,1] in the incomplete beta function (got x=%1%).", x, pol);
1412 // Now the corner cases:
1416 return (a > 1) ? 0 :
1417 (a == 1) ? 1 / boost::math::beta(a, b, pol) : policies::raise_overflow_error<T>(function, 0, pol);
1421 return (b > 1) ? 0 :
1422 (b == 1) ? 1 / boost::math::beta(a, b, pol) : policies::raise_overflow_error<T>(function, 0, pol);
1425 // Now the regular cases:
1427 typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
1429 T f1 = ibeta_power_terms<T>(a, b, x, 1 - x, lanczos_type(), true, pol, 1 / y, function);
1433 // Some forwarding functions that dis-ambiguate the third argument type:
1435 template <class RT1, class RT2, class Policy>
1436 inline typename tools::promote_args<RT1, RT2>::type
1437 beta(RT1 a, RT2 b, const Policy&, const mpl::true_*)
1439 BOOST_FPU_EXCEPTION_GUARD
1440 typedef typename tools::promote_args<RT1, RT2>::type result_type;
1441 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1442 typedef typename lanczos::lanczos<value_type, Policy>::type evaluation_type;
1443 typedef typename policies::normalise<
1445 policies::promote_float<false>,
1446 policies::promote_double<false>,
1447 policies::discrete_quantile<>,
1448 policies::assert_undefined<> >::type forwarding_policy;
1450 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::beta_imp(static_cast<value_type>(a), static_cast<value_type>(b), evaluation_type(), forwarding_policy()), "boost::math::beta<%1%>(%1%,%1%)");
1452 template <class RT1, class RT2, class RT3>
1453 inline typename tools::promote_args<RT1, RT2, RT3>::type
1454 beta(RT1 a, RT2 b, RT3 x, const mpl::false_*)
1456 return boost::math::beta(a, b, x, policies::policy<>());
1458 } // namespace detail
1461 // The actual function entry-points now follow, these just figure out
1462 // which Lanczos approximation to use
1463 // and forward to the implementation functions:
1465 template <class RT1, class RT2, class A>
1466 inline typename tools::promote_args<RT1, RT2, A>::type
1467 beta(RT1 a, RT2 b, A arg)
1469 typedef typename policies::is_policy<A>::type tag;
1470 return boost::math::detail::beta(a, b, arg, static_cast<tag*>(0));
1473 template <class RT1, class RT2>
1474 inline typename tools::promote_args<RT1, RT2>::type
1477 return boost::math::beta(a, b, policies::policy<>());
1480 template <class RT1, class RT2, class RT3, class Policy>
1481 inline typename tools::promote_args<RT1, RT2, RT3>::type
1482 beta(RT1 a, RT2 b, RT3 x, const Policy&)
1484 BOOST_FPU_EXCEPTION_GUARD
1485 typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;
1486 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1487 typedef typename policies::normalise<
1489 policies::promote_float<false>,
1490 policies::promote_double<false>,
1491 policies::discrete_quantile<>,
1492 policies::assert_undefined<> >::type forwarding_policy;
1494 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy(), false, false), "boost::math::beta<%1%>(%1%,%1%,%1%)");
1497 template <class RT1, class RT2, class RT3, class Policy>
1498 inline typename tools::promote_args<RT1, RT2, RT3>::type
1499 betac(RT1 a, RT2 b, RT3 x, const Policy&)
1501 BOOST_FPU_EXCEPTION_GUARD
1502 typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;
1503 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1504 typedef typename policies::normalise<
1506 policies::promote_float<false>,
1507 policies::promote_double<false>,
1508 policies::discrete_quantile<>,
1509 policies::assert_undefined<> >::type forwarding_policy;
1511 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy(), true, false), "boost::math::betac<%1%>(%1%,%1%,%1%)");
1513 template <class RT1, class RT2, class RT3>
1514 inline typename tools::promote_args<RT1, RT2, RT3>::type
1515 betac(RT1 a, RT2 b, RT3 x)
1517 return boost::math::betac(a, b, x, policies::policy<>());
1520 template <class RT1, class RT2, class RT3, class Policy>
1521 inline typename tools::promote_args<RT1, RT2, RT3>::type
1522 ibeta(RT1 a, RT2 b, RT3 x, const Policy&)
1524 BOOST_FPU_EXCEPTION_GUARD
1525 typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;
1526 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1527 typedef typename policies::normalise<
1529 policies::promote_float<false>,
1530 policies::promote_double<false>,
1531 policies::discrete_quantile<>,
1532 policies::assert_undefined<> >::type forwarding_policy;
1534 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy(), false, true), "boost::math::ibeta<%1%>(%1%,%1%,%1%)");
1536 template <class RT1, class RT2, class RT3>
1537 inline typename tools::promote_args<RT1, RT2, RT3>::type
1538 ibeta(RT1 a, RT2 b, RT3 x)
1540 return boost::math::ibeta(a, b, x, policies::policy<>());
1543 template <class RT1, class RT2, class RT3, class Policy>
1544 inline typename tools::promote_args<RT1, RT2, RT3>::type
1545 ibetac(RT1 a, RT2 b, RT3 x, const Policy&)
1547 BOOST_FPU_EXCEPTION_GUARD
1548 typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;
1549 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1550 typedef typename policies::normalise<
1552 policies::promote_float<false>,
1553 policies::promote_double<false>,
1554 policies::discrete_quantile<>,
1555 policies::assert_undefined<> >::type forwarding_policy;
1557 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy(), true, true), "boost::math::ibetac<%1%>(%1%,%1%,%1%)");
1559 template <class RT1, class RT2, class RT3>
1560 inline typename tools::promote_args<RT1, RT2, RT3>::type
1561 ibetac(RT1 a, RT2 b, RT3 x)
1563 return boost::math::ibetac(a, b, x, policies::policy<>());
1566 template <class RT1, class RT2, class RT3, class Policy>
1567 inline typename tools::promote_args<RT1, RT2, RT3>::type
1568 ibeta_derivative(RT1 a, RT2 b, RT3 x, const Policy&)
1570 BOOST_FPU_EXCEPTION_GUARD
1571 typedef typename tools::promote_args<RT1, RT2, RT3>::type result_type;
1572 typedef typename policies::evaluation<result_type, Policy>::type value_type;
1573 typedef typename policies::normalise<
1575 policies::promote_float<false>,
1576 policies::promote_double<false>,
1577 policies::discrete_quantile<>,
1578 policies::assert_undefined<> >::type forwarding_policy;
1580 return policies::checked_narrowing_cast<result_type, forwarding_policy>(detail::ibeta_derivative_imp(static_cast<value_type>(a), static_cast<value_type>(b), static_cast<value_type>(x), forwarding_policy()), "boost::math::ibeta_derivative<%1%>(%1%,%1%,%1%)");
1582 template <class RT1, class RT2, class RT3>
1583 inline typename tools::promote_args<RT1, RT2, RT3>::type
1584 ibeta_derivative(RT1 a, RT2 b, RT3 x)
1586 return boost::math::ibeta_derivative(a, b, x, policies::policy<>());
1590 } // namespace boost
1592 #include <boost/math/special_functions/detail/ibeta_inverse.hpp>
1593 #include <boost/math/special_functions/detail/ibeta_inv_ab.hpp>
1595 #endif // BOOST_MATH_SPECIAL_BETA_HPP