-
Notifications
You must be signed in to change notification settings - Fork 220
/
beta.hpp
1751 lines (1641 loc) · 59.8 KB
/
beta.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// (C) Copyright John Maddock 2006.
// (C) Copyright Matt Borland 2024.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_MATH_SPECIAL_BETA_HPP
#define BOOST_MATH_SPECIAL_BETA_HPP
#ifdef _MSC_VER
#pragma once
#endif
#include <boost/math/tools/config.hpp>
#include <boost/math/tools/type_traits.hpp>
#include <boost/math/tools/assert.hpp>
#include <boost/math/tools/precision.hpp>
#include <boost/math/tools/numeric_limits.hpp>
#include <boost/math/tools/tuple.hpp>
#include <boost/math/tools/promotion.hpp>
#include <boost/math/tools/cstdint.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/erf.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/expm1.hpp>
#include <boost/math/special_functions/trunc.hpp>
#include <boost/math/special_functions/lanczos.hpp>
#include <boost/math/policies/policy.hpp>
#include <boost/math/policies/error_handling.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/math_fwd.hpp>
#include <boost/math/special_functions/binomial.hpp>
#include <boost/math/special_functions/factorials.hpp>
#include <boost/math/tools/roots.hpp>
namespace boost{ namespace math{
namespace detail{
//
// Implementation of Beta(a,b) using the Lanczos approximation:
//
template <class T, class Lanczos, class Policy>
BOOST_MATH_GPU_ENABLED T beta_imp(T a, T b, const Lanczos&, const Policy& pol)
{
BOOST_MATH_STD_USING // for ADL of std names
if(a <= 0)
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);
if(b <= 0)
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);
T result; // LCOV_EXCL_LINE
T prefix = 1;
T c = a + b;
// Special cases:
if((c == a) && (b < tools::epsilon<T>()))
return 1 / b;
else if((c == b) && (a < tools::epsilon<T>()))
return 1 / a;
if(b == 1)
return 1/a;
else if(a == 1)
return 1/b;
else if(c < tools::epsilon<T>())
{
result = c / a;
result /= b;
return result;
}
/*
//
// This code appears to be no longer necessary: it was
// used to offset errors introduced from the Lanczos
// approximation, but the current Lanczos approximations
// are sufficiently accurate for all z that we can ditch
// this. It remains in the file for future reference...
//
// If a or b are less than 1, shift to greater than 1:
if(a < 1)
{
prefix *= c / a;
c += 1;
a += 1;
}
if(b < 1)
{
prefix *= c / b;
c += 1;
b += 1;
}
*/
if(a < b)
{
BOOST_MATH_GPU_SAFE_SWAP(a, b);
}
// Lanczos calculation:
T agh = static_cast<T>(a + Lanczos::g() - 0.5f);
T bgh = static_cast<T>(b + Lanczos::g() - 0.5f);
T cgh = static_cast<T>(c + Lanczos::g() - 0.5f);
result = Lanczos::lanczos_sum_expG_scaled(a) * (Lanczos::lanczos_sum_expG_scaled(b) / Lanczos::lanczos_sum_expG_scaled(c));
T ambh = a - 0.5f - b;
if((fabs(b * ambh) < (cgh * 100)) && (a > 100))
{
// Special case where the base of the power term is close to 1
// compute (1+x)^y instead:
result *= exp(ambh * boost::math::log1p(-b / cgh, pol));
}
else
{
result *= pow(agh / cgh, a - T(0.5) - b);
}
if(cgh > 1e10f)
// this avoids possible overflow, but appears to be marginally less accurate:
result *= pow((agh / cgh) * (bgh / cgh), b);
else
result *= pow((agh * bgh) / (cgh * cgh), b);
result *= sqrt(boost::math::constants::e<T>() / bgh);
// If a and b were originally less than 1 we need to scale the result:
result *= prefix;
return result;
} // template <class T, class Lanczos> beta_imp(T a, T b, const Lanczos&)
//
// Generic implementation of Beta(a,b) without Lanczos approximation support
// (Caution this is slow!!!):
//
#ifndef BOOST_MATH_HAS_GPU_SUPPORT
template <class T, class Policy>
BOOST_MATH_GPU_ENABLED T beta_imp(T a, T b, const lanczos::undefined_lanczos& l, const Policy& pol)
{
BOOST_MATH_STD_USING
if(a <= 0)
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);
if(b <= 0)
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);
const T c = a + b;
// Special cases:
if ((c == a) && (b < tools::epsilon<T>()))
return 1 / b;
else if ((c == b) && (a < tools::epsilon<T>()))
return 1 / a;
if (b == 1)
return 1 / a;
else if (a == 1)
return 1 / b;
else if (c < tools::epsilon<T>())
{
T result = c / a;
result /= b;
return result;
}
// Regular cases start here:
const T min_sterling = minimum_argument_for_bernoulli_recursion<T>();
long shift_a = 0;
long shift_b = 0;
if(a < min_sterling)
shift_a = 1 + ltrunc(min_sterling - a);
if(b < min_sterling)
shift_b = 1 + ltrunc(min_sterling - b);
long shift_c = shift_a + shift_b;
if ((shift_a == 0) && (shift_b == 0))
{
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);
}
else if ((a < 1) && (b < 1))
{
return boost::math::tgamma(a, pol) * (boost::math::tgamma(b, pol) / boost::math::tgamma(c));
}
else if(a < 1)
return boost::math::tgamma(a, pol) * boost::math::tgamma_delta_ratio(b, a, pol);
else if(b < 1)
return boost::math::tgamma(b, pol) * boost::math::tgamma_delta_ratio(a, b, pol);
else
{
T result = beta_imp(T(a + shift_a), T(b + shift_b), l, pol);
//
// Recursion:
//
for (long i = 0; i < shift_c; ++i)
{
result *= c + i;
if (i < shift_a)
result /= a + i;
if (i < shift_b)
result /= b + i;
}
return result;
}
} // template <class T>T beta_imp(T a, T b, const lanczos::undefined_lanczos& l)
#endif
//
// Compute the leading power terms in the incomplete Beta:
//
// (x^a)(y^b)/Beta(a,b) when normalised, and
// (x^a)(y^b) otherwise.
//
// Almost all of the error in the incomplete beta comes from this
// function: particularly when a and b are large. Computing large
// powers are *hard* though, and using logarithms just leads to
// horrendous cancellation errors.
//
template <class T, class Lanczos, class Policy>
BOOST_MATH_GPU_ENABLED T ibeta_power_terms(T a,
T b,
T x,
T y,
const Lanczos&,
bool normalised,
const Policy& pol,
T prefix = 1,
const char* function = "boost::math::ibeta<%1%>(%1%, %1%, %1%)")
{
BOOST_MATH_STD_USING
if(!normalised)
{
// can we do better here?
return pow(x, a) * pow(y, b);
}
T result; // LCOV_EXCL_LINE
T c = a + b;
// combine power terms with Lanczos approximation:
T agh = static_cast<T>(a + Lanczos::g() - 0.5f);
T bgh = static_cast<T>(b + Lanczos::g() - 0.5f);
T cgh = static_cast<T>(c + Lanczos::g() - 0.5f);
if ((a < tools::min_value<T>()) || (b < tools::min_value<T>()))
result = 0; // denominator overflows in this case
else
result = Lanczos::lanczos_sum_expG_scaled(c) / (Lanczos::lanczos_sum_expG_scaled(a) * Lanczos::lanczos_sum_expG_scaled(b));
result *= prefix;
// combine with the leftover terms from the Lanczos approximation:
result *= sqrt(bgh / boost::math::constants::e<T>());
result *= sqrt(agh / cgh);
// l1 and l2 are the base of the exponents minus one:
T l1 = (x * b - y * agh) / agh;
T l2 = (y * a - x * bgh) / bgh;
if((BOOST_MATH_GPU_SAFE_MIN(fabs(l1), fabs(l2)) < 0.2))
{
// when the base of the exponent is very near 1 we get really
// gross errors unless extra care is taken:
if((l1 * l2 > 0) || (BOOST_MATH_GPU_SAFE_MIN(a, b) < 1))
{
//
// This first branch handles the simple cases where either:
//
// * The two power terms both go in the same direction
// (towards zero or towards infinity). In this case if either
// term overflows or underflows, then the product of the two must
// do so also.
// *Alternatively if one exponent is less than one, then we
// can't productively use it to eliminate overflow or underflow
// from the other term. Problems with spurious overflow/underflow
// can't be ruled out in this case, but it is *very* unlikely
// since one of the power terms will evaluate to a number close to 1.
//
if(fabs(l1) < 0.1)
{
result *= exp(a * boost::math::log1p(l1, pol));
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
else
{
result *= pow((x * cgh) / agh, a);
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
if(fabs(l2) < 0.1)
{
result *= exp(b * boost::math::log1p(l2, pol));
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
else
{
result *= pow((y * cgh) / bgh, b);
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
}
else if(BOOST_MATH_GPU_SAFE_MAX(fabs(l1), fabs(l2)) < 0.5)
{
//
// Both exponents are near one and both the exponents are
// greater than one and further these two
// power terms tend in opposite directions (one towards zero,
// the other towards infinity), so we have to combine the terms
// to avoid any risk of overflow or underflow.
//
// We do this by moving one power term inside the other, we have:
//
// (1 + l1)^a * (1 + l2)^b
// = ((1 + l1)*(1 + l2)^(b/a))^a
// = (1 + l1 + l3 + l1*l3)^a ; l3 = (1 + l2)^(b/a) - 1
// = exp((b/a) * log(1 + l2)) - 1
//
// The tricky bit is deciding which term to move inside :-)
// By preference we move the larger term inside, so that the
// size of the largest exponent is reduced. However, that can
// only be done as long as l3 (see above) is also small.
//
bool small_a = a < b;
T ratio = b / a;
if((small_a && (ratio * l2 < 0.1)) || (!small_a && (l1 / ratio > 0.1)))
{
T l3 = boost::math::expm1(ratio * boost::math::log1p(l2, pol), pol);
l3 = l1 + l3 + l3 * l1;
l3 = a * boost::math::log1p(l3, pol);
result *= exp(l3);
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
else
{
T l3 = boost::math::expm1(boost::math::log1p(l1, pol) / ratio, pol);
l3 = l2 + l3 + l3 * l2;
l3 = b * boost::math::log1p(l3, pol);
result *= exp(l3);
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
}
else if(fabs(l1) < fabs(l2))
{
// First base near 1 only:
T l = a * boost::math::log1p(l1, pol)
+ b * log((y * cgh) / bgh);
if((l <= tools::log_min_value<T>()) || (l >= tools::log_max_value<T>()))
{
l += log(result);
if(l >= tools::log_max_value<T>())
return policies::raise_overflow_error<T>(function, nullptr, pol); // LCOV_EXCL_LINE we can probably never get here, probably!
result = exp(l);
}
else
result *= exp(l);
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
else
{
// Second base near 1 only:
T l = b * boost::math::log1p(l2, pol)
+ a * log((x * cgh) / agh);
if((l <= tools::log_min_value<T>()) || (l >= tools::log_max_value<T>()))
{
l += log(result);
if(l >= tools::log_max_value<T>())
return policies::raise_overflow_error<T>(function, nullptr, pol); // LCOV_EXCL_LINE we can probably never get here, probably!
result = exp(l);
}
else
result *= exp(l);
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
}
else
{
// general case:
T b1 = (x * cgh) / agh;
T b2 = (y * cgh) / bgh;
l1 = a * log(b1);
l2 = b * log(b2);
BOOST_MATH_INSTRUMENT_VARIABLE(b1);
BOOST_MATH_INSTRUMENT_VARIABLE(b2);
BOOST_MATH_INSTRUMENT_VARIABLE(l1);
BOOST_MATH_INSTRUMENT_VARIABLE(l2);
if((l1 >= tools::log_max_value<T>())
|| (l1 <= tools::log_min_value<T>())
|| (l2 >= tools::log_max_value<T>())
|| (l2 <= tools::log_min_value<T>())
)
{
// Oops, under/overflow, sidestep if we can:
if(a < b)
{
T p1 = pow(b2, b / a);
T l3 = (b1 != 0) && (p1 != 0) ? (a * (log(b1) + log(p1))) : tools::max_value<T>(); // arbitrary large value if the logs would fail!
if((l3 < tools::log_max_value<T>())
&& (l3 > tools::log_min_value<T>()))
{
result *= pow(p1 * b1, a);
}
else
{
l2 += l1 + log(result);
if(l2 >= tools::log_max_value<T>())
return policies::raise_overflow_error<T>(function, nullptr, pol); // LCOV_EXCL_LINE we can probably never get here, probably!
result = exp(l2);
}
}
else
{
// This protects against spurious overflow in a/b:
T p1 = (b1 < 1) && (b < 1) && (tools::max_value<T>() * b < a) ? static_cast<T>(0) : static_cast<T>(pow(b1, a / b));
T l3 = (p1 != 0) && (b2 != 0) ? (log(p1) + log(b2)) * b : tools::max_value<T>(); // arbitrary large value if the logs would fail!
if((l3 < tools::log_max_value<T>())
&& (l3 > tools::log_min_value<T>()))
{
result *= pow(p1 * b2, b);
}
else if(result != 0) // we can elude the calculation below if we're already going to be zero
{
l2 += l1 + log(result);
if(l2 >= tools::log_max_value<T>())
return policies::raise_overflow_error<T>(function, nullptr, pol); // LCOV_EXCL_LINE we can probably never get here, probably!
result = exp(l2);
}
}
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
else
{
// finally the normal case:
result *= pow(b1, a) * pow(b2, b);
BOOST_MATH_INSTRUMENT_VARIABLE(result);
}
}
BOOST_MATH_INSTRUMENT_VARIABLE(result);
if (0 == result)
{
if ((a > 1) && (x == 0))
return result; // true zero LCOV_EXCL_LINE we can probably never get here
if ((b > 1) && (y == 0))
return result; // true zero LCOV_EXCL_LINE we can probably never get here
return boost::math::policies::raise_underflow_error<T>(function, nullptr, pol);
}
return result;
}
//
// Compute the leading power terms in the incomplete Beta:
//
// (x^a)(y^b)/Beta(a,b) when normalised, and
// (x^a)(y^b) otherwise.
//
// Almost all of the error in the incomplete beta comes from this
// function: particularly when a and b are large. Computing large
// powers are *hard* though, and using logarithms just leads to
// horrendous cancellation errors.
//
// This version is generic, slow, and does not use the Lanczos approximation.
//
#ifndef BOOST_MATH_HAS_GPU_SUPPORT
template <class T, class Policy>
BOOST_MATH_GPU_ENABLED T ibeta_power_terms(T a,
T b,
T x,
T y,
const boost::math::lanczos::undefined_lanczos& l,
bool normalised,
const Policy& pol,
T prefix = 1,
const char* = "boost::math::ibeta<%1%>(%1%, %1%, %1%)")
{
BOOST_MATH_STD_USING
if(!normalised)
{
return prefix * pow(x, a) * pow(y, b);
}
T c = a + b;
const T min_sterling = minimum_argument_for_bernoulli_recursion<T>();
long shift_a = 0;
long shift_b = 0;
if (a < min_sterling)
shift_a = 1 + ltrunc(min_sterling - a);
if (b < min_sterling)
shift_b = 1 + ltrunc(min_sterling - b);
if ((shift_a == 0) && (shift_b == 0))
{
T power1, power2;
bool need_logs = false;
if (a < b)
{
BOOST_MATH_IF_CONSTEXPR(boost::math::numeric_limits<T>::has_infinity)
{
power1 = pow((x * y * c * c) / (a * b), a);
power2 = pow((y * c) / b, b - a);
}
else
{
// We calculate these logs purely so we can check for overflow in the power functions
T l1 = log((x * y * c * c) / (a * b));
T l2 = log((y * c) / b);
if ((l1 * a > tools::log_min_value<T>()) && (l1 * a < tools::log_max_value<T>()) && (l2 * (b - a) < tools::log_max_value<T>()) && (l2 * (b - a) > tools::log_min_value<T>()))
{
power1 = pow((x * y * c * c) / (a * b), a);
power2 = pow((y * c) / b, b - a);
}
else
{
need_logs = true;
}
}
}
else
{
BOOST_MATH_IF_CONSTEXPR(boost::math::numeric_limits<T>::has_infinity)
{
power1 = pow((x * y * c * c) / (a * b), b);
power2 = pow((x * c) / a, a - b);
}
else
{
// We calculate these logs purely so we can check for overflow in the power functions
T l1 = log((x * y * c * c) / (a * b)) * b;
T l2 = log((x * c) / a) * (a - b);
if ((l1 * a > tools::log_min_value<T>()) && (l1 * a < tools::log_max_value<T>()) && (l2 * (b - a) < tools::log_max_value<T>()) && (l2 * (b - a) > tools::log_min_value<T>()))
{
power1 = pow((x * y * c * c) / (a * b), b);
power2 = pow((x * c) / a, a - b);
}
else
need_logs = true;
}
}
BOOST_MATH_IF_CONSTEXPR(boost::math::numeric_limits<T>::has_infinity)
{
if (!(boost::math::isnormal)(power1) || !(boost::math::isnormal)(power2))
{
need_logs = true;
}
}
if (need_logs)
{
//
// We want:
//
// (xc / a)^a (yc / b)^b
//
// But we know that one or other term will over / underflow and combining the logs will be next to useless as that will cause significant cancellation.
// If we assume b > a and express z ^ b as(z ^ b / a) ^ a with z = (yc / b) then we can move one power term inside the other :
//
// ((xc / a) * (yc / b)^(b / a))^a
//
// However, we're not quite there yet, as the term being exponentiated is quite likely to be close to unity, so let:
//
// xc / a = 1 + (xb - ya) / a
//
// analogously let :
//
// 1 + p = (yc / b) ^ (b / a) = 1 + expm1((b / a) * log1p((ya - xb) / b))
//
// so putting the two together we have :
//
// exp(a * log1p((xb - ya) / a + p + p(xb - ya) / a))
//
// Analogously, when a > b we can just swap all the terms around.
//
// Finally, there are a few cases (x or y is unity) when the above logic can't be used
// or where there is no logarithmic cancellation and accuracy is better just using
// the regular formula:
//
T xc_a = x * c / a;
T yc_b = y * c / b;
if ((x == 1) || (y == 1) || (fabs(xc_a - 1) > 0.25) || (fabs(yc_b - 1) > 0.25))
{
// The above logic fails, the result is almost certainly zero:
power1 = exp(log(xc_a) * a + log(yc_b) * b);
power2 = 1;
}
else if (b > a)
{
T p = boost::math::expm1((b / a) * boost::math::log1p((y * a - x * b) / b));
power1 = exp(a * boost::math::log1p((x * b - y * a) / a + p * (x * c / a)));
power2 = 1;
}
else
{
T p = boost::math::expm1((a / b) * boost::math::log1p((x * b - y * a) / a));
power1 = exp(b * boost::math::log1p((y * a - x * b) / b + p * (y * c / b)));
power2 = 1;
}
}
return prefix * power1 * power2 * scaled_tgamma_no_lanczos(c, pol) / (scaled_tgamma_no_lanczos(a, pol) * scaled_tgamma_no_lanczos(b, pol));
}
T power1 = pow(x, a);
T power2 = pow(y, b);
T bet = beta_imp(a, b, l, pol);
if(!(boost::math::isnormal)(power1) || !(boost::math::isnormal)(power2) || !(boost::math::isnormal)(bet))
{
int shift_c = shift_a + shift_b;
T result = ibeta_power_terms(T(a + shift_a), T(b + shift_b), x, y, l, normalised, pol, prefix);
if ((boost::math::isnormal)(result))
{
for (int i = 0; i < shift_c; ++i)
{
result /= c + i;
if (i < shift_a)
{
result *= a + i;
result /= x;
}
if (i < shift_b)
{
result *= b + i;
result /= y;
}
}
return prefix * result;
}
else
{
T log_result = log(x) * a + log(y) * b + log(prefix);
if ((boost::math::isnormal)(bet))
log_result -= log(bet);
else
log_result += boost::math::lgamma(c, pol) - boost::math::lgamma(a, pol) - boost::math::lgamma(b, pol);
return exp(log_result);
}
}
return prefix * power1 * (power2 / bet);
}
#endif
//
// Series approximation to the incomplete beta:
//
template <class T>
struct ibeta_series_t
{
typedef T result_type;
BOOST_MATH_GPU_ENABLED ibeta_series_t(T a_, T b_, T x_, T mult) : result(mult), x(x_), apn(a_), poch(1-b_), n(1) {}
BOOST_MATH_GPU_ENABLED T operator()()
{
T r = result / apn;
apn += 1;
result *= poch * x / n;
++n;
poch += 1;
return r;
}
private:
T result, x, apn, poch;
int n;
};
template <class T, class Lanczos, class Policy>
BOOST_MATH_GPU_ENABLED T ibeta_series(T a, T b, T x, T s0, const Lanczos&, bool normalised, T* p_derivative, T y, const Policy& pol)
{
BOOST_MATH_STD_USING
T result;
BOOST_MATH_ASSERT((p_derivative == 0) || normalised);
if(normalised)
{
T c = a + b;
// incomplete beta power term, combined with the Lanczos approximation:
T agh = static_cast<T>(a + Lanczos::g() - 0.5f);
T bgh = static_cast<T>(b + Lanczos::g() - 0.5f);
T cgh = static_cast<T>(c + Lanczos::g() - 0.5f);
if ((a < tools::min_value<T>()) || (b < tools::min_value<T>()))
result = 0; // denorms cause overflow in the Lanzos series, result will be zero anyway
else
result = Lanczos::lanczos_sum_expG_scaled(c) / (Lanczos::lanczos_sum_expG_scaled(a) * Lanczos::lanczos_sum_expG_scaled(b));
if (!(boost::math::isfinite)(result))
result = 0; // LCOV_EXCL_LINE we can probably never get here, covered already above?
T l1 = log(cgh / bgh) * (b - 0.5f);
T l2 = log(x * cgh / agh) * a;
//
// Check for over/underflow in the power terms:
//
if((l1 > tools::log_min_value<T>())
&& (l1 < tools::log_max_value<T>())
&& (l2 > tools::log_min_value<T>())
&& (l2 < tools::log_max_value<T>()))
{
if(a * b < bgh * 10)
result *= exp((b - 0.5f) * boost::math::log1p(a / bgh, pol));
else
result *= pow(cgh / bgh, T(b - T(0.5)));
result *= pow(x * cgh / agh, a);
result *= sqrt(agh / boost::math::constants::e<T>());
if(p_derivative)
{
*p_derivative = result * pow(y, b);
BOOST_MATH_ASSERT(*p_derivative >= 0);
}
}
else
{
//
// Oh dear, we need logs, and this *will* cancel:
//
if (result != 0) // elude calculation when result will be zero.
{
result = log(result) + l1 + l2 + (log(agh) - 1) / 2;
if (p_derivative)
*p_derivative = exp(result + b * log(y));
result = exp(result);
}
}
}
else
{
// Non-normalised, just compute the power:
result = pow(x, a);
}
if(result < tools::min_value<T>())
return s0; // Safeguard: series can't cope with denorms.
ibeta_series_t<T> s(a, b, x, result);
boost::math::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, s0);
policies::check_series_iterations<T>("boost::math::ibeta<%1%>(%1%, %1%, %1%) in ibeta_series (with lanczos)", max_iter, pol);
return result;
}
//
// Incomplete Beta series again, this time without Lanczos support:
//
#ifndef BOOST_MATH_HAS_GPU_SUPPORT
template <class T, class Policy>
BOOST_MATH_GPU_ENABLED 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)
{
BOOST_MATH_STD_USING
T result;
BOOST_MATH_ASSERT((p_derivative == 0) || normalised);
if(normalised)
{
const T min_sterling = minimum_argument_for_bernoulli_recursion<T>();
long shift_a = 0;
long shift_b = 0;
if (a < min_sterling)
shift_a = 1 + ltrunc(min_sterling - a);
if (b < min_sterling)
shift_b = 1 + ltrunc(min_sterling - b);
T c = a + b;
if ((shift_a == 0) && (shift_b == 0))
{
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));
}
else if ((a < 1) && (b > 1))
result = pow(x, a) / (boost::math::tgamma(a, pol) * boost::math::tgamma_delta_ratio(b, a, pol));
else
{
T power = pow(x, a);
T bet = beta_imp(a, b, l, pol);
if (!(boost::math::isnormal)(power) || !(boost::math::isnormal)(bet))
{
result = exp(a * log(x) + boost::math::lgamma(c, pol) - boost::math::lgamma(a, pol) - boost::math::lgamma(b, pol));
}
else
result = power / bet;
}
if(p_derivative)
{
*p_derivative = result * pow(y, b);
BOOST_MATH_ASSERT(*p_derivative >= 0);
}
}
else
{
// Non-normalised, just compute the power:
result = pow(x, a);
}
if(result < tools::min_value<T>())
return s0; // Safeguard: series can't cope with denorms.
ibeta_series_t<T> s(a, b, x, result);
boost::math::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
result = boost::math::tools::sum_series(s, boost::math::policies::get_epsilon<T, Policy>(), max_iter, s0);
policies::check_series_iterations<T>("boost::math::ibeta<%1%>(%1%, %1%, %1%) in ibeta_series (without lanczos)", max_iter, pol);
return result;
}
#endif
//
// Continued fraction for the incomplete beta:
//
template <class T>
struct ibeta_fraction2_t
{
typedef boost::math::pair<T, T> result_type;
BOOST_MATH_GPU_ENABLED ibeta_fraction2_t(T a_, T b_, T x_, T y_) : a(a_), b(b_), x(x_), y(y_), m(0) {}
BOOST_MATH_GPU_ENABLED result_type operator()()
{
T aN = (a + m - 1) * (a + b + m - 1) * m * (b - m) * x * x;
T denom = (a + 2 * m - 1);
aN /= denom * denom;
T bN = static_cast<T>(m);
bN += (m * (b - m) * x) / (a + 2*m - 1);
bN += ((a + m) * (a * y - b * x + 1 + m *(2 - x))) / (a + 2*m + 1);
++m;
return boost::math::make_pair(aN, bN);
}
private:
T a, b, x, y;
int m;
};
//
// Evaluate the incomplete beta via the continued fraction representation:
//
template <class T, class Policy>
BOOST_MATH_GPU_ENABLED inline T ibeta_fraction2(T a, T b, T x, T y, const Policy& pol, bool normalised, T* p_derivative)
{
typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
BOOST_MATH_STD_USING
T result = ibeta_power_terms(a, b, x, y, lanczos_type(), normalised, pol);
if(p_derivative)
{
*p_derivative = result;
BOOST_MATH_ASSERT(*p_derivative >= 0);
}
if(result == 0)
return result;
ibeta_fraction2_t<T> f(a, b, x, y);
T fract = boost::math::tools::continued_fraction_b(f, boost::math::policies::get_epsilon<T, Policy>());
BOOST_MATH_INSTRUMENT_VARIABLE(fract);
BOOST_MATH_INSTRUMENT_VARIABLE(result);
return result / fract;
}
//
// Computes the difference between ibeta(a,b,x) and ibeta(a+k,b,x):
//
template <class T, class Policy>
BOOST_MATH_GPU_ENABLED T ibeta_a_step(T a, T b, T x, T y, int k, const Policy& pol, bool normalised, T* p_derivative)
{
typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
BOOST_MATH_INSTRUMENT_VARIABLE(k);
T prefix = ibeta_power_terms(a, b, x, y, lanczos_type(), normalised, pol);
if(p_derivative)
{
*p_derivative = prefix;
BOOST_MATH_ASSERT(*p_derivative >= 0);
}
prefix /= a;
if(prefix == 0)
return prefix;
T sum = 1;
T term = 1;
// series summation from 0 to k-1:
for(int i = 0; i < k-1; ++i)
{
term *= (a+b+i) * x / (a+i+1);
sum += term;
}
prefix *= sum;
return prefix;
}
//
// This function is only needed for the non-regular incomplete beta,
// it computes the delta in:
// beta(a,b,x) = prefix + delta * beta(a+k,b,x)
// it is currently only called for small k.
//
template <class T>
BOOST_MATH_GPU_ENABLED inline T rising_factorial_ratio(T a, T b, int k)
{
// calculate:
// (a)(a+1)(a+2)...(a+k-1)
// _______________________
// (b)(b+1)(b+2)...(b+k-1)
// This is only called with small k, for large k
// it is grossly inefficient, do not use outside it's
// intended purpose!!!
BOOST_MATH_INSTRUMENT_VARIABLE(k);
BOOST_MATH_ASSERT(k > 0);
T result = 1;
for(int i = 0; i < k; ++i)
result *= (a+i) / (b+i);
return result;
}
//
// Routine for a > 15, b < 1
//
// Begin by figuring out how large our table of Pn's should be,
// quoted accuracies are "guesstimates" based on empirical observation.
// Note that the table size should never exceed the size of our
// tables of factorials.
//
template <class T>
struct Pn_size
{
// This is likely to be enough for ~35-50 digit accuracy
// but it's hard to quantify exactly:
#ifndef BOOST_MATH_HAS_NVRTC
static constexpr unsigned value =
::boost::math::max_factorial<T>::value >= 100 ? 50
: ::boost::math::max_factorial<T>::value >= ::boost::math::max_factorial<double>::value ? 30
: ::boost::math::max_factorial<T>::value >= ::boost::math::max_factorial<float>::value ? 15 : 1;
static_assert(::boost::math::max_factorial<T>::value >= ::boost::math::max_factorial<float>::value, "Type does not provide for 35-50 digits of accuracy.");
#else
static constexpr unsigned value = 0; // Will never be called
#endif
};
template <>
struct Pn_size<float>
{
static constexpr unsigned value = 15; // ~8-15 digit accuracy
#ifndef BOOST_MATH_HAS_GPU_SUPPORT
static_assert(::boost::math::max_factorial<float>::value >= 30, "Type does not provide for 8-15 digits of accuracy.");
#endif
};
template <>
struct Pn_size<double>
{
static constexpr unsigned value = 30; // 16-20 digit accuracy
#ifndef BOOST_MATH_HAS_GPU_SUPPORT
static_assert(::boost::math::max_factorial<double>::value >= 60, "Type does not provide for 16-20 digits of accuracy.");
#endif
};
template <>
struct Pn_size<long double>
{
static constexpr unsigned value = 50; // ~35-50 digit accuracy
#ifndef BOOST_MATH_HAS_GPU_SUPPORT
static_assert(::boost::math::max_factorial<long double>::value >= 100, "Type does not provide for ~35-50 digits of accuracy");
#endif
};
template <class T, class Policy>
BOOST_MATH_GPU_ENABLED T beta_small_b_large_a_series(T a, T b, T x, T y, T s0, T mult, const Policy& pol, bool normalised)
{
typedef typename lanczos::lanczos<T, Policy>::type lanczos_type;
BOOST_MATH_STD_USING
//
// This is DiDonato and Morris's BGRAT routine, see Eq's 9 through 9.6.
//
// Some values we'll need later, these are Eq 9.1:
//
T bm1 = b - 1;
T t = a + bm1 / 2;
T lx, u; // LCOV_EXCL_LINE
if(y < 0.35)
lx = boost::math::log1p(-y, pol);
else
lx = log(x);
u = -t * lx;
// and from from 9.2:
T prefix; // LCOV_EXCL_LINE
T h = regularised_gamma_prefix(b, u, pol, lanczos_type());
if(h <= tools::min_value<T>())
return s0;
if(normalised)
{
prefix = h / boost::math::tgamma_delta_ratio(a, b, pol);
prefix /= pow(t, b);
}
else
{
prefix = full_igamma_prefix(b, u, pol) / pow(t, b);
}
prefix *= mult;
//
// now we need the quantity Pn, unfortunately this is computed
// recursively, and requires a full history of all the previous values
// so no choice but to declare a big table and hope it's big enough...
//
T p[ ::boost::math::detail::Pn_size<T>::value ] = { 1 }; // see 9.3.
//
// Now an initial value for J, see 9.6:
//
T j = boost::math::gamma_q(b, u, pol) / h;
//