non_central_chi_squared.hpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. // boost\math\distributions\non_central_chi_squared.hpp
  2. // Copyright John Maddock 2008.
  3. // Use, modification and distribution are subject to the
  4. // Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt
  6. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. #ifndef BOOST_MATH_SPECIAL_NON_CENTRAL_CHI_SQUARE_HPP
  8. #define BOOST_MATH_SPECIAL_NON_CENTRAL_CHI_SQUARE_HPP
  9. #include <boost/math/distributions/fwd.hpp>
  10. #include <boost/math/special_functions/gamma.hpp> // for incomplete gamma. gamma_q
  11. #include <boost/math/special_functions/bessel.hpp> // for cyl_bessel_i
  12. #include <boost/math/special_functions/round.hpp> // for iround
  13. #include <boost/math/distributions/complement.hpp> // complements
  14. #include <boost/math/distributions/chi_squared.hpp> // central distribution
  15. #include <boost/math/distributions/detail/common_error_handling.hpp> // error checks
  16. #include <boost/math/special_functions/fpclassify.hpp> // isnan.
  17. #include <boost/math/tools/roots.hpp> // for root finding.
  18. #include <boost/math/distributions/detail/generic_mode.hpp>
  19. #include <boost/math/distributions/detail/generic_quantile.hpp>
  20. namespace boost
  21. {
  22. namespace math
  23. {
  24. template <class RealType, class Policy>
  25. class non_central_chi_squared_distribution;
  26. namespace detail{
  27. template <class T, class Policy>
  28. T non_central_chi_square_q(T x, T f, T theta, const Policy& pol, T init_sum = 0)
  29. {
  30. //
  31. // Computes the complement of the Non-Central Chi-Square
  32. // Distribution CDF by summing a weighted sum of complements
  33. // of the central-distributions. The weighting factor is
  34. // a Poisson Distribution.
  35. //
  36. // This is an application of the technique described in:
  37. //
  38. // Computing discrete mixtures of continuous
  39. // distributions: noncentral chisquare, noncentral t
  40. // and the distribution of the square of the sample
  41. // multiple correlation coeficient.
  42. // D. Benton, K. Krishnamoorthy.
  43. // Computational Statistics & Data Analysis 43 (2003) 249 - 267
  44. //
  45. BOOST_MATH_STD_USING
  46. // Special case:
  47. if(x == 0)
  48. return 1;
  49. //
  50. // Initialize the variables we'll be using:
  51. //
  52. T lambda = theta / 2;
  53. T del = f / 2;
  54. T y = x / 2;
  55. boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
  56. T errtol = boost::math::policies::get_epsilon<T, Policy>();
  57. T sum = init_sum;
  58. //
  59. // k is the starting location for iteration, we'll
  60. // move both forwards and backwards from this point.
  61. // k is chosen as the peek of the Poisson weights, which
  62. // will occur *before* the largest term.
  63. //
  64. int k = iround(lambda, pol);
  65. // Forwards and backwards Poisson weights:
  66. T poisf = boost::math::gamma_p_derivative(1 + k, lambda, pol);
  67. T poisb = poisf * k / lambda;
  68. // Initial forwards central chi squared term:
  69. T gamf = boost::math::gamma_q(del + k, y, pol);
  70. // Forwards and backwards recursion terms on the central chi squared:
  71. T xtermf = boost::math::gamma_p_derivative(del + 1 + k, y, pol);
  72. T xtermb = xtermf * (del + k) / y;
  73. // Initial backwards central chi squared term:
  74. T gamb = gamf - xtermb;
  75. //
  76. // Forwards iteration first, this is the
  77. // stable direction for the gamma function
  78. // recurrences:
  79. //
  80. int i;
  81. for(i = k; static_cast<boost::uintmax_t>(i-k) < max_iter; ++i)
  82. {
  83. T term = poisf * gamf;
  84. sum += term;
  85. poisf *= lambda / (i + 1);
  86. gamf += xtermf;
  87. xtermf *= y / (del + i + 1);
  88. if(((sum == 0) || (fabs(term / sum) < errtol)) && (term >= poisf * gamf))
  89. break;
  90. }
  91. //Error check:
  92. if(static_cast<boost::uintmax_t>(i-k) >= max_iter)
  93. policies::raise_evaluation_error(
  94. "cdf(non_central_chi_squared_distribution<%1%>, %1%)",
  95. "Series did not converge, closest value was %1%", sum, pol);
  96. //
  97. // Now backwards iteration: the gamma
  98. // function recurrences are unstable in this
  99. // direction, we rely on the terms deminishing in size
  100. // faster than we introduce cancellation errors.
  101. // For this reason it's very important that we start
  102. // *before* the largest term so that backwards iteration
  103. // is strictly converging.
  104. //
  105. for(i = k - 1; i >= 0; --i)
  106. {
  107. T term = poisb * gamb;
  108. sum += term;
  109. poisb *= i / lambda;
  110. xtermb *= (del + i) / y;
  111. gamb -= xtermb;
  112. if((sum == 0) || (fabs(term / sum) < errtol))
  113. break;
  114. }
  115. return sum;
  116. }
  117. template <class T, class Policy>
  118. T non_central_chi_square_p_ding(T x, T f, T theta, const Policy& pol, T init_sum = 0)
  119. {
  120. //
  121. // This is an implementation of:
  122. //
  123. // Algorithm AS 275:
  124. // Computing the Non-Central #2 Distribution Function
  125. // Cherng G. Ding
  126. // Applied Statistics, Vol. 41, No. 2. (1992), pp. 478-482.
  127. //
  128. // This uses a stable forward iteration to sum the
  129. // CDF, unfortunately this can not be used for large
  130. // values of the non-centrality parameter because:
  131. // * The first term may underfow to zero.
  132. // * We may need an extra-ordinary number of terms
  133. // before we reach the first *significant* term.
  134. //
  135. BOOST_MATH_STD_USING
  136. // Special case:
  137. if(x == 0)
  138. return 0;
  139. T tk = boost::math::gamma_p_derivative(f/2 + 1, x/2, pol);
  140. T lambda = theta / 2;
  141. T vk = exp(-lambda);
  142. T uk = vk;
  143. T sum = init_sum + tk * vk;
  144. if(sum == 0)
  145. return sum;
  146. boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
  147. T errtol = boost::math::policies::get_epsilon<T, Policy>();
  148. int i;
  149. T lterm(0), term(0);
  150. for(i = 1; static_cast<boost::uintmax_t>(i) < max_iter; ++i)
  151. {
  152. tk = tk * x / (f + 2 * i);
  153. uk = uk * lambda / i;
  154. vk = vk + uk;
  155. lterm = term;
  156. term = vk * tk;
  157. sum += term;
  158. if((fabs(term / sum) < errtol) && (term <= lterm))
  159. break;
  160. }
  161. //Error check:
  162. if(static_cast<boost::uintmax_t>(i) >= max_iter)
  163. policies::raise_evaluation_error(
  164. "cdf(non_central_chi_squared_distribution<%1%>, %1%)",
  165. "Series did not converge, closest value was %1%", sum, pol);
  166. return sum;
  167. }
  168. template <class T, class Policy>
  169. T non_central_chi_square_p(T y, T n, T lambda, const Policy& pol, T init_sum)
  170. {
  171. //
  172. // This is taken more or less directly from:
  173. //
  174. // Computing discrete mixtures of continuous
  175. // distributions: noncentral chisquare, noncentral t
  176. // and the distribution of the square of the sample
  177. // multiple correlation coeficient.
  178. // D. Benton, K. Krishnamoorthy.
  179. // Computational Statistics & Data Analysis 43 (2003) 249 - 267
  180. //
  181. // We're summing a Poisson weighting term multiplied by
  182. // a central chi squared distribution.
  183. //
  184. BOOST_MATH_STD_USING
  185. // Special case:
  186. if(y == 0)
  187. return 0;
  188. boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
  189. T errtol = boost::math::policies::get_epsilon<T, Policy>();
  190. T errorf(0), errorb(0);
  191. T x = y / 2;
  192. T del = lambda / 2;
  193. //
  194. // Starting location for the iteration, we'll iterate
  195. // both forwards and backwards from this point. The
  196. // location chosen is the maximum of the Poisson weight
  197. // function, which ocurrs *after* the largest term in the
  198. // sum.
  199. //
  200. int k = iround(del, pol);
  201. T a = n / 2 + k;
  202. // Central chi squared term for forward iteration:
  203. T gamkf = boost::math::gamma_p(a, x, pol);
  204. if(lambda == 0)
  205. return gamkf;
  206. // Central chi squared term for backward iteration:
  207. T gamkb = gamkf;
  208. // Forwards Poisson weight:
  209. T poiskf = gamma_p_derivative(k+1, del, pol);
  210. // Backwards Poisson weight:
  211. T poiskb = poiskf;
  212. // Forwards gamma function recursion term:
  213. T xtermf = boost::math::gamma_p_derivative(a, x, pol);
  214. // Backwards gamma function recursion term:
  215. T xtermb = xtermf * x / a;
  216. T sum = init_sum + poiskf * gamkf;
  217. if(sum == 0)
  218. return sum;
  219. int i = 1;
  220. //
  221. // Backwards recursion first, this is the stable
  222. // direction for gamma function recurrences:
  223. //
  224. while(i <= k)
  225. {
  226. xtermb *= (a - i + 1) / x;
  227. gamkb += xtermb;
  228. poiskb = poiskb * (k - i + 1) / del;
  229. errorf = errorb;
  230. errorb = gamkb * poiskb;
  231. sum += errorb;
  232. if((fabs(errorb / sum) < errtol) && (errorb <= errorf))
  233. break;
  234. ++i;
  235. }
  236. i = 1;
  237. //
  238. // Now forwards recursion, the gamma function
  239. // recurrence relation is unstable in this direction,
  240. // so we rely on the magnitude of successive terms
  241. // decreasing faster than we introduce cancellation error.
  242. // For this reason it's vital that k is chosen to be *after*
  243. // the largest term, so that successive forward iterations
  244. // are strictly (and rapidly) converging.
  245. //
  246. do
  247. {
  248. xtermf = xtermf * x / (a + i - 1);
  249. gamkf = gamkf - xtermf;
  250. poiskf = poiskf * del / (k + i);
  251. errorf = poiskf * gamkf;
  252. sum += errorf;
  253. ++i;
  254. }while((fabs(errorf / sum) > errtol) && (static_cast<boost::uintmax_t>(i) < max_iter));
  255. //Error check:
  256. if(static_cast<boost::uintmax_t>(i) >= max_iter)
  257. policies::raise_evaluation_error(
  258. "cdf(non_central_chi_squared_distribution<%1%>, %1%)",
  259. "Series did not converge, closest value was %1%", sum, pol);
  260. return sum;
  261. }
  262. template <class T, class Policy>
  263. T non_central_chi_square_pdf(T x, T n, T lambda, const Policy& pol)
  264. {
  265. //
  266. // As above but for the PDF:
  267. //
  268. BOOST_MATH_STD_USING
  269. boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
  270. T errtol = boost::math::policies::get_epsilon<T, Policy>();
  271. T x2 = x / 2;
  272. T n2 = n / 2;
  273. T l2 = lambda / 2;
  274. T sum = 0;
  275. int k = itrunc(l2);
  276. T pois = gamma_p_derivative(k + 1, l2, pol) * gamma_p_derivative(n2 + k, x2);
  277. if(pois == 0)
  278. return 0;
  279. T poisb = pois;
  280. for(int i = k; ; ++i)
  281. {
  282. sum += pois;
  283. if(pois / sum < errtol)
  284. break;
  285. if(static_cast<boost::uintmax_t>(i - k) >= max_iter)
  286. return policies::raise_evaluation_error(
  287. "pdf(non_central_chi_squared_distribution<%1%>, %1%)",
  288. "Series did not converge, closest value was %1%", sum, pol);
  289. pois *= l2 * x2 / ((i + 1) * (n2 + i));
  290. }
  291. for(int i = k - 1; i >= 0; --i)
  292. {
  293. poisb *= (i + 1) * (n2 + i) / (l2 * x2);
  294. sum += poisb;
  295. if(poisb / sum < errtol)
  296. break;
  297. }
  298. return sum / 2;
  299. }
  300. template <class RealType, class Policy>
  301. inline RealType non_central_chi_squared_cdf(RealType x, RealType k, RealType l, bool invert, const Policy&)
  302. {
  303. typedef typename policies::evaluation<RealType, Policy>::type value_type;
  304. typedef typename policies::normalise<
  305. Policy,
  306. policies::promote_float<false>,
  307. policies::promote_double<false>,
  308. policies::discrete_quantile<>,
  309. policies::assert_undefined<> >::type forwarding_policy;
  310. BOOST_MATH_STD_USING
  311. value_type result;
  312. if(l == 0)
  313. result = cdf(boost::math::chi_squared_distribution<RealType, Policy>(k), x);
  314. else if(x > k + l)
  315. {
  316. // Complement is the smaller of the two:
  317. result = detail::non_central_chi_square_q(
  318. static_cast<value_type>(x),
  319. static_cast<value_type>(k),
  320. static_cast<value_type>(l),
  321. forwarding_policy(),
  322. static_cast<value_type>(invert ? 0 : -1));
  323. invert = !invert;
  324. }
  325. else if(l < 200)
  326. {
  327. // For small values of the non-centrality parameter
  328. // we can use Ding's method:
  329. result = detail::non_central_chi_square_p_ding(
  330. static_cast<value_type>(x),
  331. static_cast<value_type>(k),
  332. static_cast<value_type>(l),
  333. forwarding_policy(),
  334. static_cast<value_type>(invert ? -1 : 0));
  335. }
  336. else
  337. {
  338. // For largers values of the non-centrality
  339. // parameter Ding's method will consume an
  340. // extra-ordinary number of terms, and worse
  341. // may return zero when the result is in fact
  342. // finite, use Krishnamoorthy's method instead:
  343. result = detail::non_central_chi_square_p(
  344. static_cast<value_type>(x),
  345. static_cast<value_type>(k),
  346. static_cast<value_type>(l),
  347. forwarding_policy(),
  348. static_cast<value_type>(invert ? -1 : 0));
  349. }
  350. if(invert)
  351. result = -result;
  352. return policies::checked_narrowing_cast<RealType, forwarding_policy>(
  353. result,
  354. "boost::math::non_central_chi_squared_cdf<%1%>(%1%, %1%, %1%)");
  355. }
  356. template <class T, class Policy>
  357. struct nccs_quantile_functor
  358. {
  359. nccs_quantile_functor(const non_central_chi_squared_distribution<T,Policy>& d, T t, bool c)
  360. : dist(d), target(t), comp(c) {}
  361. T operator()(const T& x)
  362. {
  363. return comp ?
  364. target - cdf(complement(dist, x))
  365. : cdf(dist, x) - target;
  366. }
  367. private:
  368. non_central_chi_squared_distribution<T,Policy> dist;
  369. T target;
  370. bool comp;
  371. };
  372. template <class RealType, class Policy>
  373. RealType nccs_quantile(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& p, bool comp)
  374. {
  375. BOOST_MATH_STD_USING
  376. static const char* function = "quantile(non_central_chi_squared_distribution<%1%>, %1%)";
  377. typedef typename policies::evaluation<RealType, Policy>::type value_type;
  378. typedef typename policies::normalise<
  379. Policy,
  380. policies::promote_float<false>,
  381. policies::promote_double<false>,
  382. policies::discrete_quantile<>,
  383. policies::assert_undefined<> >::type forwarding_policy;
  384. value_type k = dist.degrees_of_freedom();
  385. value_type l = dist.non_centrality();
  386. value_type r;
  387. if(!detail::check_df(
  388. function,
  389. k, &r, Policy())
  390. ||
  391. !detail::check_non_centrality(
  392. function,
  393. l,
  394. &r,
  395. Policy())
  396. ||
  397. !detail::check_probability(
  398. function,
  399. static_cast<value_type>(p),
  400. &r,
  401. Policy()))
  402. return (RealType)r;
  403. //
  404. // Special cases get short-circuited first:
  405. //
  406. if(p == 0)
  407. return comp ? tools::max_value<RealType>() : 0;
  408. if(p == 1)
  409. return comp ? 0 : tools::max_value<RealType>();
  410. //
  411. // This is Pearson's approximation to the quantile, see
  412. // Pearson, E. S. (1959) "Note on an approximation to the distribution of
  413. // noncentral chi squared", Biometrika 46: 364.
  414. // See also:
  415. // "A comparison of approximations to percentiles of the noncentral chi2-distribution",
  416. // Hardeo Sahai and Mario Miguel Ojeda, Revista de Matematica: Teoria y Aplicaciones 2003 10(1–2) : 57–76.
  417. // Note that the latter reference refers to an approximation of the CDF, when they really mean the quantile.
  418. //
  419. value_type b = -(l * l) / (k + 3 * l);
  420. value_type c = (k + 3 * l) / (k + 2 * l);
  421. value_type ff = (k + 2 * l) / (c * c);
  422. value_type guess;
  423. if(comp)
  424. {
  425. guess = b + c * quantile(complement(chi_squared_distribution<value_type, forwarding_policy>(ff), p));
  426. }
  427. else
  428. {
  429. guess = b + c * quantile(chi_squared_distribution<value_type, forwarding_policy>(ff), p);
  430. }
  431. //
  432. // Sometimes guess goes very small or negative, in that case we have
  433. // to do something else for the initial guess, this approximation
  434. // was provided in a private communication from Thomas Luu, PhD candidate,
  435. // University College London. It's an asymptotic expansion for the
  436. // quantile which usually gets us within an order of magnitude of the
  437. // correct answer.
  438. //
  439. if(guess < 0.005)
  440. {
  441. value_type pp = comp ? 1 - p : p;
  442. //guess = pow(pow(value_type(2), (k / 2 - 1)) * exp(l / 2) * pp * k, 2 / k);
  443. guess = pow(pow(value_type(2), (k / 2 - 1)) * exp(l / 2) * pp * k * boost::math::tgamma(k / 2, forwarding_policy()), (2 / k));
  444. if(guess == 0)
  445. guess = tools::min_value<value_type>();
  446. }
  447. value_type result = detail::generic_quantile(
  448. non_central_chi_squared_distribution<value_type, forwarding_policy>(k, l),
  449. p,
  450. guess,
  451. comp,
  452. function);
  453. return policies::checked_narrowing_cast<RealType, forwarding_policy>(
  454. result,
  455. function);
  456. }
  457. template <class RealType, class Policy>
  458. RealType nccs_pdf(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)
  459. {
  460. BOOST_MATH_STD_USING
  461. static const char* function = "pdf(non_central_chi_squared_distribution<%1%>, %1%)";
  462. typedef typename policies::evaluation<RealType, Policy>::type value_type;
  463. typedef typename policies::normalise<
  464. Policy,
  465. policies::promote_float<false>,
  466. policies::promote_double<false>,
  467. policies::discrete_quantile<>,
  468. policies::assert_undefined<> >::type forwarding_policy;
  469. value_type k = dist.degrees_of_freedom();
  470. value_type l = dist.non_centrality();
  471. value_type r;
  472. if(!detail::check_df(
  473. function,
  474. k, &r, Policy())
  475. ||
  476. !detail::check_non_centrality(
  477. function,
  478. l,
  479. &r,
  480. Policy())
  481. ||
  482. !detail::check_positive_x(
  483. function,
  484. (value_type)x,
  485. &r,
  486. Policy()))
  487. return (RealType)r;
  488. if(l == 0)
  489. return pdf(boost::math::chi_squared_distribution<RealType, forwarding_policy>(dist.degrees_of_freedom()), x);
  490. // Special case:
  491. if(x == 0)
  492. return 0;
  493. if(l > 50)
  494. {
  495. r = non_central_chi_square_pdf(static_cast<value_type>(x), k, l, forwarding_policy());
  496. }
  497. else
  498. {
  499. r = log(x / l) * (k / 4 - 0.5f) - (x + l) / 2;
  500. if(fabs(r) >= tools::log_max_value<RealType>() / 4)
  501. {
  502. r = non_central_chi_square_pdf(static_cast<value_type>(x), k, l, forwarding_policy());
  503. }
  504. else
  505. {
  506. r = exp(r);
  507. r = 0.5f * r
  508. * boost::math::cyl_bessel_i(k/2 - 1, sqrt(l * x), forwarding_policy());
  509. }
  510. }
  511. return policies::checked_narrowing_cast<RealType, forwarding_policy>(
  512. r,
  513. function);
  514. }
  515. template <class RealType, class Policy>
  516. struct degrees_of_freedom_finder
  517. {
  518. degrees_of_freedom_finder(
  519. RealType lam_, RealType x_, RealType p_, bool c)
  520. : lam(lam_), x(x_), p(p_), comp(c) {}
  521. RealType operator()(const RealType& v)
  522. {
  523. non_central_chi_squared_distribution<RealType, Policy> d(v, lam);
  524. return comp ?
  525. RealType(p - cdf(complement(d, x)))
  526. : RealType(cdf(d, x) - p);
  527. }
  528. private:
  529. RealType lam;
  530. RealType x;
  531. RealType p;
  532. bool comp;
  533. };
  534. template <class RealType, class Policy>
  535. inline RealType find_degrees_of_freedom(
  536. RealType lam, RealType x, RealType p, RealType q, const Policy& pol)
  537. {
  538. const char* function = "non_central_chi_squared<%1%>::find_degrees_of_freedom";
  539. if((p == 0) || (q == 0))
  540. {
  541. //
  542. // Can't a thing if one of p and q is zero:
  543. //
  544. return policies::raise_evaluation_error<RealType>(function,
  545. "Can't find degrees of freedom when the probability is 0 or 1, only possible answer is %1%",
  546. RealType(std::numeric_limits<RealType>::quiet_NaN()), Policy());
  547. }
  548. degrees_of_freedom_finder<RealType, Policy> f(lam, x, p < q ? p : q, p < q ? false : true);
  549. tools::eps_tolerance<RealType> tol(policies::digits<RealType, Policy>());
  550. boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
  551. //
  552. // Pick an initial guess that we know will give us a probability
  553. // right around 0.5.
  554. //
  555. RealType guess = x - lam;
  556. if(guess < 1)
  557. guess = 1;
  558. std::pair<RealType, RealType> ir = tools::bracket_and_solve_root(
  559. f, guess, RealType(2), false, tol, max_iter, pol);
  560. RealType result = ir.first + (ir.second - ir.first) / 2;
  561. if(max_iter >= policies::get_max_root_iterations<Policy>())
  562. {
  563. policies::raise_evaluation_error<RealType>(function, "Unable to locate solution in a reasonable time:"
  564. " or there is no answer to problem. Current best guess is %1%", result, Policy());
  565. }
  566. return result;
  567. }
  568. template <class RealType, class Policy>
  569. struct non_centrality_finder
  570. {
  571. non_centrality_finder(
  572. RealType v_, RealType x_, RealType p_, bool c)
  573. : v(v_), x(x_), p(p_), comp(c) {}
  574. RealType operator()(const RealType& lam)
  575. {
  576. non_central_chi_squared_distribution<RealType, Policy> d(v, lam);
  577. return comp ?
  578. RealType(p - cdf(complement(d, x)))
  579. : RealType(cdf(d, x) - p);
  580. }
  581. private:
  582. RealType v;
  583. RealType x;
  584. RealType p;
  585. bool comp;
  586. };
  587. template <class RealType, class Policy>
  588. inline RealType find_non_centrality(
  589. RealType v, RealType x, RealType p, RealType q, const Policy& pol)
  590. {
  591. const char* function = "non_central_chi_squared<%1%>::find_non_centrality";
  592. if((p == 0) || (q == 0))
  593. {
  594. //
  595. // Can't do a thing if one of p and q is zero:
  596. //
  597. return policies::raise_evaluation_error<RealType>(function,
  598. "Can't find non centrality parameter when the probability is 0 or 1, only possible answer is %1%",
  599. RealType(std::numeric_limits<RealType>::quiet_NaN()), Policy());
  600. }
  601. non_centrality_finder<RealType, Policy> f(v, x, p < q ? p : q, p < q ? false : true);
  602. tools::eps_tolerance<RealType> tol(policies::digits<RealType, Policy>());
  603. boost::uintmax_t max_iter = policies::get_max_root_iterations<Policy>();
  604. //
  605. // Pick an initial guess that we know will give us a probability
  606. // right around 0.5.
  607. //
  608. RealType guess = x - v;
  609. if(guess < 1)
  610. guess = 1;
  611. std::pair<RealType, RealType> ir = tools::bracket_and_solve_root(
  612. f, guess, RealType(2), false, tol, max_iter, pol);
  613. RealType result = ir.first + (ir.second - ir.first) / 2;
  614. if(max_iter >= policies::get_max_root_iterations<Policy>())
  615. {
  616. policies::raise_evaluation_error<RealType>(function, "Unable to locate solution in a reasonable time:"
  617. " or there is no answer to problem. Current best guess is %1%", result, Policy());
  618. }
  619. return result;
  620. }
  621. }
  622. template <class RealType = double, class Policy = policies::policy<> >
  623. class non_central_chi_squared_distribution
  624. {
  625. public:
  626. typedef RealType value_type;
  627. typedef Policy policy_type;
  628. non_central_chi_squared_distribution(RealType df_, RealType lambda) : df(df_), ncp(lambda)
  629. {
  630. const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::non_central_chi_squared_distribution(%1%,%1%)";
  631. RealType r;
  632. detail::check_df(
  633. function,
  634. df, &r, Policy());
  635. detail::check_non_centrality(
  636. function,
  637. ncp,
  638. &r,
  639. Policy());
  640. } // non_central_chi_squared_distribution constructor.
  641. RealType degrees_of_freedom() const
  642. { // Private data getter function.
  643. return df;
  644. }
  645. RealType non_centrality() const
  646. { // Private data getter function.
  647. return ncp;
  648. }
  649. static RealType find_degrees_of_freedom(RealType lam, RealType x, RealType p)
  650. {
  651. const char* function = "non_central_chi_squared<%1%>::find_degrees_of_freedom";
  652. typedef typename policies::evaluation<RealType, Policy>::type value_type;
  653. typedef typename policies::normalise<
  654. Policy,
  655. policies::promote_float<false>,
  656. policies::promote_double<false>,
  657. policies::discrete_quantile<>,
  658. policies::assert_undefined<> >::type forwarding_policy;
  659. value_type result = detail::find_degrees_of_freedom(
  660. static_cast<value_type>(lam),
  661. static_cast<value_type>(x),
  662. static_cast<value_type>(p),
  663. static_cast<value_type>(1-p),
  664. forwarding_policy());
  665. return policies::checked_narrowing_cast<RealType, forwarding_policy>(
  666. result,
  667. function);
  668. }
  669. template <class A, class B, class C>
  670. static RealType find_degrees_of_freedom(const complemented3_type<A,B,C>& c)
  671. {
  672. const char* function = "non_central_chi_squared<%1%>::find_degrees_of_freedom";
  673. typedef typename policies::evaluation<RealType, Policy>::type value_type;
  674. typedef typename policies::normalise<
  675. Policy,
  676. policies::promote_float<false>,
  677. policies::promote_double<false>,
  678. policies::discrete_quantile<>,
  679. policies::assert_undefined<> >::type forwarding_policy;
  680. value_type result = detail::find_degrees_of_freedom(
  681. static_cast<value_type>(c.dist),
  682. static_cast<value_type>(c.param1),
  683. static_cast<value_type>(1-c.param2),
  684. static_cast<value_type>(c.param2),
  685. forwarding_policy());
  686. return policies::checked_narrowing_cast<RealType, forwarding_policy>(
  687. result,
  688. function);
  689. }
  690. static RealType find_non_centrality(RealType v, RealType x, RealType p)
  691. {
  692. const char* function = "non_central_chi_squared<%1%>::find_non_centrality";
  693. typedef typename policies::evaluation<RealType, Policy>::type value_type;
  694. typedef typename policies::normalise<
  695. Policy,
  696. policies::promote_float<false>,
  697. policies::promote_double<false>,
  698. policies::discrete_quantile<>,
  699. policies::assert_undefined<> >::type forwarding_policy;
  700. value_type result = detail::find_non_centrality(
  701. static_cast<value_type>(v),
  702. static_cast<value_type>(x),
  703. static_cast<value_type>(p),
  704. static_cast<value_type>(1-p),
  705. forwarding_policy());
  706. return policies::checked_narrowing_cast<RealType, forwarding_policy>(
  707. result,
  708. function);
  709. }
  710. template <class A, class B, class C>
  711. static RealType find_non_centrality(const complemented3_type<A,B,C>& c)
  712. {
  713. const char* function = "non_central_chi_squared<%1%>::find_non_centrality";
  714. typedef typename policies::evaluation<RealType, Policy>::type value_type;
  715. typedef typename policies::normalise<
  716. Policy,
  717. policies::promote_float<false>,
  718. policies::promote_double<false>,
  719. policies::discrete_quantile<>,
  720. policies::assert_undefined<> >::type forwarding_policy;
  721. value_type result = detail::find_non_centrality(
  722. static_cast<value_type>(c.dist),
  723. static_cast<value_type>(c.param1),
  724. static_cast<value_type>(1-c.param2),
  725. static_cast<value_type>(c.param2),
  726. forwarding_policy());
  727. return policies::checked_narrowing_cast<RealType, forwarding_policy>(
  728. result,
  729. function);
  730. }
  731. private:
  732. // Data member, initialized by constructor.
  733. RealType df; // degrees of freedom.
  734. RealType ncp; // non-centrality parameter
  735. }; // template <class RealType, class Policy> class non_central_chi_squared_distribution
  736. typedef non_central_chi_squared_distribution<double> non_central_chi_squared; // Reserved name of type double.
  737. // Non-member functions to give properties of the distribution.
  738. template <class RealType, class Policy>
  739. inline const std::pair<RealType, RealType> range(const non_central_chi_squared_distribution<RealType, Policy>& /* dist */)
  740. { // Range of permissible values for random variable k.
  741. using boost::math::tools::max_value;
  742. return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>()); // Max integer?
  743. }
  744. template <class RealType, class Policy>
  745. inline const std::pair<RealType, RealType> support(const non_central_chi_squared_distribution<RealType, Policy>& /* dist */)
  746. { // Range of supported values for random variable k.
  747. // This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
  748. using boost::math::tools::max_value;
  749. return std::pair<RealType, RealType>(static_cast<RealType>(0), max_value<RealType>());
  750. }
  751. template <class RealType, class Policy>
  752. inline RealType mean(const non_central_chi_squared_distribution<RealType, Policy>& dist)
  753. { // Mean of poisson distribution = lambda.
  754. const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::mean()";
  755. RealType k = dist.degrees_of_freedom();
  756. RealType l = dist.non_centrality();
  757. RealType r;
  758. if(!detail::check_df(
  759. function,
  760. k, &r, Policy())
  761. ||
  762. !detail::check_non_centrality(
  763. function,
  764. l,
  765. &r,
  766. Policy()))
  767. return r;
  768. return k + l;
  769. } // mean
  770. template <class RealType, class Policy>
  771. inline RealType mode(const non_central_chi_squared_distribution<RealType, Policy>& dist)
  772. { // mode.
  773. static const char* function = "mode(non_central_chi_squared_distribution<%1%> const&)";
  774. RealType k = dist.degrees_of_freedom();
  775. RealType l = dist.non_centrality();
  776. RealType r;
  777. if(!detail::check_df(
  778. function,
  779. k, &r, Policy())
  780. ||
  781. !detail::check_non_centrality(
  782. function,
  783. l,
  784. &r,
  785. Policy()))
  786. return (RealType)r;
  787. return detail::generic_find_mode(dist, 1 + k, function);
  788. }
  789. template <class RealType, class Policy>
  790. inline RealType variance(const non_central_chi_squared_distribution<RealType, Policy>& dist)
  791. { // variance.
  792. const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::variance()";
  793. RealType k = dist.degrees_of_freedom();
  794. RealType l = dist.non_centrality();
  795. RealType r;
  796. if(!detail::check_df(
  797. function,
  798. k, &r, Policy())
  799. ||
  800. !detail::check_non_centrality(
  801. function,
  802. l,
  803. &r,
  804. Policy()))
  805. return r;
  806. return 2 * (2 * l + k);
  807. }
  808. // RealType standard_deviation(const non_central_chi_squared_distribution<RealType, Policy>& dist)
  809. // standard_deviation provided by derived accessors.
  810. template <class RealType, class Policy>
  811. inline RealType skewness(const non_central_chi_squared_distribution<RealType, Policy>& dist)
  812. { // skewness = sqrt(l).
  813. const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::skewness()";
  814. RealType k = dist.degrees_of_freedom();
  815. RealType l = dist.non_centrality();
  816. RealType r;
  817. if(!detail::check_df(
  818. function,
  819. k, &r, Policy())
  820. ||
  821. !detail::check_non_centrality(
  822. function,
  823. l,
  824. &r,
  825. Policy()))
  826. return r;
  827. BOOST_MATH_STD_USING
  828. return pow(2 / (k + 2 * l), RealType(3)/2) * (k + 3 * l);
  829. }
  830. template <class RealType, class Policy>
  831. inline RealType kurtosis_excess(const non_central_chi_squared_distribution<RealType, Policy>& dist)
  832. {
  833. const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::kurtosis_excess()";
  834. RealType k = dist.degrees_of_freedom();
  835. RealType l = dist.non_centrality();
  836. RealType r;
  837. if(!detail::check_df(
  838. function,
  839. k, &r, Policy())
  840. ||
  841. !detail::check_non_centrality(
  842. function,
  843. l,
  844. &r,
  845. Policy()))
  846. return r;
  847. return 12 * (k + 4 * l) / ((k + 2 * l) * (k + 2 * l));
  848. } // kurtosis_excess
  849. template <class RealType, class Policy>
  850. inline RealType kurtosis(const non_central_chi_squared_distribution<RealType, Policy>& dist)
  851. {
  852. return kurtosis_excess(dist) + 3;
  853. }
  854. template <class RealType, class Policy>
  855. inline RealType pdf(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)
  856. { // Probability Density/Mass Function.
  857. return detail::nccs_pdf(dist, x);
  858. } // pdf
  859. template <class RealType, class Policy>
  860. RealType cdf(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& x)
  861. {
  862. const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::cdf(%1%)";
  863. RealType k = dist.degrees_of_freedom();
  864. RealType l = dist.non_centrality();
  865. RealType r;
  866. if(!detail::check_df(
  867. function,
  868. k, &r, Policy())
  869. ||
  870. !detail::check_non_centrality(
  871. function,
  872. l,
  873. &r,
  874. Policy())
  875. ||
  876. !detail::check_positive_x(
  877. function,
  878. x,
  879. &r,
  880. Policy()))
  881. return r;
  882. return detail::non_central_chi_squared_cdf(x, k, l, false, Policy());
  883. } // cdf
  884. template <class RealType, class Policy>
  885. RealType cdf(const complemented2_type<non_central_chi_squared_distribution<RealType, Policy>, RealType>& c)
  886. { // Complemented Cumulative Distribution Function
  887. const char* function = "boost::math::non_central_chi_squared_distribution<%1%>::cdf(%1%)";
  888. non_central_chi_squared_distribution<RealType, Policy> const& dist = c.dist;
  889. RealType x = c.param;
  890. RealType k = dist.degrees_of_freedom();
  891. RealType l = dist.non_centrality();
  892. RealType r;
  893. if(!detail::check_df(
  894. function,
  895. k, &r, Policy())
  896. ||
  897. !detail::check_non_centrality(
  898. function,
  899. l,
  900. &r,
  901. Policy())
  902. ||
  903. !detail::check_positive_x(
  904. function,
  905. x,
  906. &r,
  907. Policy()))
  908. return r;
  909. return detail::non_central_chi_squared_cdf(x, k, l, true, Policy());
  910. } // ccdf
  911. template <class RealType, class Policy>
  912. inline RealType quantile(const non_central_chi_squared_distribution<RealType, Policy>& dist, const RealType& p)
  913. { // Quantile (or Percent Point) function.
  914. return detail::nccs_quantile(dist, p, false);
  915. } // quantile
  916. template <class RealType, class Policy>
  917. inline RealType quantile(const complemented2_type<non_central_chi_squared_distribution<RealType, Policy>, RealType>& c)
  918. { // Quantile (or Percent Point) function.
  919. return detail::nccs_quantile(c.dist, c.param, true);
  920. } // quantile complement.
  921. } // namespace math
  922. } // namespace boost
  923. // This include must be at the end, *after* the accessors
  924. // for this distribution have been defined, in order to
  925. // keep compilers that support two-phase lookup happy.
  926. #include <boost/math/distributions/detail/derived_accessors.hpp>
  927. #endif // BOOST_MATH_SPECIAL_NON_CENTRAL_CHI_SQUARE_HPP