-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgamma_from_R.cpp
1549 lines (1362 loc) · 44.4 KB
/
pgamma_from_R.cpp
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
/* Scalefactor:= (2^32)^8 = 2^256 = 1.157921e+77 */
#include <math.h>
#include <float.h>
#include <stdio.h>
#include <iostream>
/*
* Mathlib : A C Library of Special Functions
* Copyright (C) 2005-6 Morten Welinder <terra@gnome.org>
* Copyright (C) 2005-10 The R Foundation
* Copyright (C) 2006-2015 The R Core Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* https://www.R-project.org/Licenses/
*
* SYNOPSIS
*
* #include <Rmath.h>
*
* double pgamma (double x, double alph, double scale,
* int lower_tail, int log_p)
*
* double log1pmx (double x)
* double lgamma1p (double a)
*
* double logspace_add (double logx, double logy)
* double logspace_sub (double logx, double logy)
* double logspace_sum (double* logx, int n)
*
*
* DESCRIPTION
*
* This function computes the distribution function for the
* gamma distribution with shape parameter alph and scale parameter
* scale. This is also known as the incomplete gamma function.
* See Abramowitz and Stegun (6.5.1) for example.
*
* NOTES
*
* Complete redesign by Morten Welinder, originally for Gnumeric.
* Improvements (e.g. "while NEEDED_SCALE") by Martin Maechler
*
* REFERENCES
*
*/
/*----------- DEBUGGING -------------
* make CFLAGS='-DDEBUG_p -g'
* (cd `R-devel RHOME`/src/nmath; gcc -I. -I../../src/include -I../../../R/src/include -DHAVE_CONFIG_H -fopenmp -DDEBUG_p -g -c ../../../R/src/nmath/pgamma.c -o pgamma.o)
*/
/* Scalefactor:= (2^32)^8 = 2^256 = 1.157921e+77 */
#define M_LN_SQRT_2PI 0.918938533204672741780329736406 /* log(sqrt(2*pi)) */
#define R_Log1_Exp(x) ((x) > -M_LN2 ? log(-expm1(x)) : log1p(-exp(x)))
#define give_log log_p
#define R_D__0 (log_p ? -INFINITY : 0.)
#define R_D__1 (log_p ? 0. : 1.) /* 1 */
#define R_D_exp(x) (log_p ? (x) : exp(x)) /* exp(x) */
#define SQR(x) ((x)*(x))
#define R_D_fexp(f,x) (give_log ? -0.5*log(f)+(x) : exp(x)/sqrt(f))
static const double scalefactor = SQR(SQR(SQR(4294967296.0)));
#undef SQR
#ifdef HAVE_LONG_DOUBLE
# define LDOUBLE long double
#else
# define LDOUBLE double
#endif
#ifdef HAVE_NEARYINT
# define R_forceint(x) nearbyint()
#else
# define R_forceint(x) round(x)
#endif
#define R_P_bounds_01(x, x_min, x_max) \
if(x <= x_min) return R_DT_0; \
/* If |x| > |k| * M_cutoff, then log[ exp(-x) * k^x ] =~= -x */
static const double M_cutoff = M_LN2 * DBL_MAX_EXP / DBL_EPSILON;/*=3.196577e18*/
/* Continued fraction for calculation of
* 1/i + x/(i+d) + x^2/(i+2*d) + x^3/(i+3*d) + ... = sum_{k=0}^Inf x^k/(i+k*d)
*
* auxilary in log1pmx() and lgamma1p()
*/
#ifdef HAVE_VISIBILITY_ATTRIBUTE
# define attribute_hidden __attribute__ ((visibility ("hidden")))
#else
# define attribute_hidden
#endif
#define M_LN_SQRT_PId2 0.225791352644727432363097614947
#define M_2PI 6.28318530717958647692528676655900576
#define M_1_SQRT_2PI 0.398942280401432677939946059934 /* 1/sqrt(2pi) */
#define M_SQRT_32 5.656854249492380195206754896838
#define R_DT_0 (lower_tail ? R_D__0 : R_D__1) /* 0 */
#define R_DT_1 (lower_tail ? R_D__1 : R_D__0) /* 1 */
#ifdef HAVE_SINPI
#elif defined HAVE___SINPI
double sinpi(double x) {
return __sinpi(x);
}
#else
// sin(pi * x) -- exact when x = k/2 for all integer k
double sinpi(double x) {
#ifdef IEEE_754
if (ISNAN(x)) return x;
#endif
if(isinf(x)) return std::numeric_limits<double>::quiet_NaN();
x = fmod(x, 2.); // sin(pi(x + 2k)) == sin(pi x) for all integer k
// map (-2,2) --> (-1,1] :
if(x <= -1) x += 2.; else if (x > 1.) x -= 2.;
if(x == 0. || x == 1.) return 0.;
if(x == 0.5) return 1.;
if(x == -0.5) return -1.;
// otherwise
return sin(M_PI * x);
}
#endif
double dnorm(double x, double mu, double sigma, int give_log)
{
#ifdef IEEE_754
if (ISNAN(x) || ISNAN(mu) || ISNAN(sigma))
return x + mu + sigma;
#endif
if(isinf(sigma)) return R_D__0;
if(isinf(x) && mu == x) return std::numeric_limits<double>::quiet_NaN();/* x-mu is NaN */
if (sigma <= 0) {
if (sigma < 0){
throw("Nan");
return std::numeric_limits<double>::quiet_NaN();
}
/* sigma == 0 */
return (x == mu) ? +INFINITY : R_D__0;
}
x = (x - mu) / sigma;
if(isinf(x)) return R_D__0;
x = fabs (x);
if (x >= 2 * sqrt(DBL_MAX)) return R_D__0;
if (give_log)
return -(M_LN_SQRT_2PI + 0.5 * x * x + log(sigma));
// M_1_SQRT_2PI = 1 / sqrt(2 * pi)
#ifdef MATHLIB_FAST_dnorm
// and for R <= 3.0.x and R-devel upto 2014-01-01:
return M_1_SQRT_2PI * exp(-0.5 * x * x) / sigma;
#else
// more accurate, less fast :
if (x < 5) return M_1_SQRT_2PI * exp(-0.5 * x * x) / sigma;
/* ELSE:
* x*x may lose upto about two digits accuracy for "large" x
* Morten Welinder's proposal for PR#15620
* https://bugs.r-project.org/bugzilla/show_bug.cgi?id=15620
* -- 1 -- No hoop jumping when we underflow to zero anyway:
* -x^2/2 < log(2)*.Machine$double.min.exp <==>
* x > sqrt(-2*log(2)*.Machine$double.min.exp) =IEEE= 37.64031
* but "thanks" to denormalized numbers, underflow happens a bit later,
* effective.D.MIN.EXP <- with(.Machine, double.min.exp + double.ulp.digits)
* for IEEE, DBL_MIN_EXP is -1022 but "effective" is -1074
* ==> boundary = sqrt(-2*log(2)*(.Machine$double.min.exp + .Machine$double.ulp.digits))
* =IEEE= 38.58601
* [on one x86_64 platform, effective boundary a bit lower: 38.56804]
*/
if (x > sqrt(-2*M_LN2*(DBL_MIN_EXP + 1-DBL_MANT_DIG))) return 0.;
/* Now, to get full accurary, split x into two parts,
* x = x1+x2, such that |x2| <= 2^-16.
* Assuming that we are using IEEE doubles, that means that
* x1*x1 is error free for x<1024 (but we have x < 38.6 anyway).
* If we do not have IEEE this is still an improvement over the naive formula.
*/
double x1 = // R_forceint(x * 65536) / 65536 =
ldexp( R_forceint(ldexp(x, 16)), -16);
double x2 = x - x1;
return M_1_SQRT_2PI / sigma *
(exp(-0.5 * x1 * x1) * exp( (-0.5 * x2 - x1) * x2 ) );
#endif
}
double attribute_hidden chebyshev_eval(double x, const double *a, const int n)
{
double b0, b1, b2, twox;
int i;
if (n < 1 || n > 1000) return std::numeric_limits<double>::quiet_NaN();
if (x < -1.1 || x > 1.1) return std::numeric_limits<double>::quiet_NaN();
twox = x * 2;
b2 = b1 = 0;
b0 = 0;
for (i = 1; i <= n; i++) {
b2 = b1;
b1 = b0;
b0 = twox * b1 - b2 + a[n - i];
}
return (b0 - b2) * 0.5;
}
double attribute_hidden lgammacor(double x)
{
const static double algmcs[15] = {
+.1666389480451863247205729650822e+0,
-.1384948176067563840732986059135e-4,
+.9810825646924729426157171547487e-8,
-.1809129475572494194263306266719e-10,
+.6221098041892605227126015543416e-13,
-.3399615005417721944303330599666e-15,
+.2683181998482698748957538846666e-17,
-.2868042435334643284144622399999e-19,
+.3962837061046434803679306666666e-21,
-.6831888753985766870111999999999e-23,
+.1429227355942498147573333333333e-24,
-.3547598158101070547199999999999e-26,
+.1025680058010470912000000000000e-27,
-.3401102254316748799999999999999e-29,
+.1276642195630062933333333333333e-30
};
double tmp;
/* For IEEE double precision DBL_EPSILON = 2^-52 = 2.220446049250313e-16 :
* xbig = 2 ^ 26.5
* xmax = DBL_MAX / 48 = 2^1020 / 3 */
#define nalgm 5
#define xbig 94906265.62425156
#define xmax 3.745194030963158e306
if (x < 10) return std::numeric_limits<double>::quiet_NaN();
else if (x >= xmax) {
throw("underflow");
/* allow to underflow below */
}
else if (x < xbig) {
tmp = 10 / x;
return chebyshev_eval(tmp * tmp * 2 - 1, algmcs, nalgm) / x;
}
return 1 / (x * 12);
}
double attribute_hidden stirlerr(double n)
{
#define S0 0.083333333333333333333 /* 1/12 */
#define S1 0.00277777777777777777778 /* 1/360 */
#define S2 0.00079365079365079365079365 /* 1/1260 */
#define S3 0.000595238095238095238095238 /* 1/1680 */
#define S4 0.0008417508417508417508417508/* 1/1188 */
/*
error for 0, 0.5, 1.0, 1.5, ..., 14.5, 15.0.
*/
const static double sferr_halves[31] = {
0.0, /* n=0 - wrong, place holder only */
0.1534264097200273452913848, /* 0.5 */
0.0810614667953272582196702, /* 1.0 */
0.0548141210519176538961390, /* 1.5 */
0.0413406959554092940938221, /* 2.0 */
0.03316287351993628748511048, /* 2.5 */
0.02767792568499833914878929, /* 3.0 */
0.02374616365629749597132920, /* 3.5 */
0.02079067210376509311152277, /* 4.0 */
0.01848845053267318523077934, /* 4.5 */
0.01664469118982119216319487, /* 5.0 */
0.01513497322191737887351255, /* 5.5 */
0.01387612882307074799874573, /* 6.0 */
0.01281046524292022692424986, /* 6.5 */
0.01189670994589177009505572, /* 7.0 */
0.01110455975820691732662991, /* 7.5 */
0.010411265261972096497478567, /* 8.0 */
0.009799416126158803298389475, /* 8.5 */
0.009255462182712732917728637, /* 9.0 */
0.008768700134139385462952823, /* 9.5 */
0.008330563433362871256469318, /* 10.0 */
0.007934114564314020547248100, /* 10.5 */
0.007573675487951840794972024, /* 11.0 */
0.007244554301320383179543912, /* 11.5 */
0.006942840107209529865664152, /* 12.0 */
0.006665247032707682442354394, /* 12.5 */
0.006408994188004207068439631, /* 13.0 */
0.006171712263039457647532867, /* 13.5 */
0.005951370112758847735624416, /* 14.0 */
0.005746216513010115682023589, /* 14.5 */
0.005554733551962801371038690 /* 15.0 */
};
double nn;
if (n <= 15.0) {
nn = n + n;
if (nn == (int)nn) return(sferr_halves[(int)nn]);
return(lgamma(n + 1.) - (n + 0.5)*log(n) + n - M_LN_SQRT_2PI);
}
nn = n*n;
if (n>500) return((S0-S1/nn)/n);
if (n> 80) return((S0-(S1-S2/nn)/nn)/n);
if (n> 35) return((S0-(S1-(S2-S3/nn)/nn)/nn)/n);
/* 15 < n <= 35 : */
return((S0-(S1-(S2-(S3-S4/nn)/nn)/nn)/nn)/n);
}
double gammafn(double x)
{
const static double gamcs[42] = {
+.8571195590989331421920062399942e-2,
+.4415381324841006757191315771652e-2,
+.5685043681599363378632664588789e-1,
-.4219835396418560501012500186624e-2,
+.1326808181212460220584006796352e-2,
-.1893024529798880432523947023886e-3,
+.3606925327441245256578082217225e-4,
-.6056761904460864218485548290365e-5,
+.1055829546302283344731823509093e-5,
-.1811967365542384048291855891166e-6,
+.3117724964715322277790254593169e-7,
-.5354219639019687140874081024347e-8,
+.9193275519859588946887786825940e-9,
-.1577941280288339761767423273953e-9,
+.2707980622934954543266540433089e-10,
-.4646818653825730144081661058933e-11,
+.7973350192007419656460767175359e-12,
-.1368078209830916025799499172309e-12,
+.2347319486563800657233471771688e-13,
-.4027432614949066932766570534699e-14,
+.6910051747372100912138336975257e-15,
-.1185584500221992907052387126192e-15,
+.2034148542496373955201026051932e-16,
-.3490054341717405849274012949108e-17,
+.5987993856485305567135051066026e-18,
-.1027378057872228074490069778431e-18,
+.1762702816060529824942759660748e-19,
-.3024320653735306260958772112042e-20,
+.5188914660218397839717833550506e-21,
-.8902770842456576692449251601066e-22,
+.1527474068493342602274596891306e-22,
-.2620731256187362900257328332799e-23,
+.4496464047830538670331046570666e-24,
-.7714712731336877911703901525333e-25,
+.1323635453126044036486572714666e-25,
-.2270999412942928816702313813333e-26,
+.3896418998003991449320816639999e-27,
-.6685198115125953327792127999999e-28,
+.1146998663140024384347613866666e-28,
-.1967938586345134677295103999999e-29,
+.3376448816585338090334890666666e-30,
-.5793070335782135784625493333333e-31
};
int i, n;
double y;
double sinpiy, value;
#ifdef NOMORE_FOR_THREADS
static int ngam = 0;
static double xmin = 0, xmax = 0., xsml = 0., dxrel = 0.;
/* Initialize machine dependent constants, the first time gamma() is called.
FIXME for threads ! */
if (ngam == 0) {
ngam = chebyshev_init(gamcs, 42, DBL_EPSILON/20);/*was .1*d1mach(3)*/
gammalims(&xmin, &xmax);/*-> ./gammalims.c */
xsml = exp(fmax2(log(DBL_MIN), -log(DBL_MAX)) + 0.01);
/* = exp(.01)*DBL_MIN = 2.247e-308 for IEEE */
dxrel = sqrt(DBL_EPSILON);/*was sqrt(d1mach(4)) */
}
#else
/* For IEEE double precision DBL_EPSILON = 2^-52 = 2.220446049250313e-16 :
* (xmin, xmax) are non-trivial, see ./gammalims.c
* xsml = exp(.01)*DBL_MIN
* dxrel = sqrt(DBL_EPSILON) = 2 ^ -26
*/
# define ngam 22
# define xmin -170.5674972726612
# define xmax 171.61447887182298
# define xsml 2.2474362225598545e-308
# define dxrel 1.490116119384765696e-8
#endif
if(isnan(x)) return x;
/* If the argument is exactly zero or a negative integer
* then return NaN. */
if (x == 0 || (x < 0 && x == round(x))) {
return std::numeric_limits<double>::quiet_NaN();
}
y = fabs(x);
if (y <= 10) {
/* Compute gamma(x) for -10 <= x <= 10
* Reduce the interval and find gamma(1 + y) for 0 <= y < 1
* first of all. */
n = (int) x;
if(x < 0) --n;
y = x - n;/* n = floor(x) ==> y in [ 0, 1 ) */
--n;
value = chebyshev_eval(y * 2 - 1, gamcs, ngam) + .9375;
if (n == 0)
return value;/* x = 1.dddd = 1+y */
if (n < 0) {
/* compute gamma(x) for -10 <= x < 1 */
/* exact 0 or "-n" checked already above */
/* The answer is less than half precision */
/* because x too near a negative integer. */
if (x < -0.5 && fabs(x - (int)(x - 0.5) / x) < dxrel) {
throw("The answer is less than half precision because x too near a negative integer.");
}
/* The argument is so close to 0 that the result would overflow. */
if (y < xsml) {
throw ("allowed range problem, the argument is so close to 0 that the result would overflow.");
if(x > 0) return +INFINITY;
else return -INFINITY;
}
n = -n;
for (i = 0; i < n; i++) {
value /= (x + i);
}
return value;
}
else {
/* gamma(x) for 2 <= x <= 10 */
for (i = 1; i <= n; i++) {
value *= (y + i);
}
return value;
}
}
else {
/* gamma(x) for y = |x| > 10. */
if (x > xmax) { /* Overflow */
throw("Overflow");
return +INFINITY;
}
if (x < xmin) { /* Underflow */
throw("Underflow");
return 0.;
}
if(y <= 50 && y == (int)y) { /* compute (n - 1)! */
value = 1.;
for (i = 2; i < y; i++) value *= i;
}
else { /* normal case */
value = exp((y - 0.5) * log(y) - y + M_LN_SQRT_2PI +
((2*y == (int)2*y)? stirlerr(y) : lgammacor(y)));
}
if (x > 0)
return value;
if (fabs((x - (int)(x - 0.5))/x) < dxrel){
/* The answer is less than half precision because */
/* the argument is too near a negative integer. */
throw("The answer is less than half precision because the argument is too near a negative integer.");
}
sinpiy = sinpi(y);
if (sinpiy == 0) { /* Negative integer arg - overflow */
throw("Negative integer arg - overflow");
return +INFINITY;
}
return -M_PI / (y * sinpiy * value);
}
}
double lgammafn_sign(double x, int *sgn)
{
double ans, y, sinpiy;
#ifdef NOMORE_FOR_THREADS
static double xmax = 0.;
static double dxrel = 0.;
if (xmax == 0) {/* initialize machine dependent constants _ONCE_ */
xmax = d1mach(2)/log(d1mach(2));/* = 2.533 e305 for IEEE double */
dxrel = sqrt (d1mach(4));/* sqrt(Eps) ~ 1.49 e-8 for IEEE double */
}
#else
/* For IEEE double precision DBL_EPSILON = 2^-52 = 2.220446049250313e-16 :
xmax = DBL_MAX / log(DBL_MAX) = 2^1024 / (1024 * log(2)) = 2^1014 / log(2)
dxrel = sqrt(DBL_EPSILON) = 2^-26 = 5^26 * 1e-26 (is *exact* below !)
*/
#define xmax 2.5327372760800758e+305
#define dxrel 1.490116119384765625e-8
#endif
if (sgn != NULL) *sgn = 1;
#ifdef IEEE_754
if(ISNAN(x)) return x;
#endif
if (sgn != NULL && x < 0 && fmod(floor(-x), 2.) == 0)
*sgn = -1;
if (x <= 0 && x == trunc(x)) { /* Negative integer argument */
throw("Negative integer argument");
return +INFINITY;/* +Inf, since lgamma(x) = log|gamma(x)| */
}
y = fabs(x);
if (y < 1e-306) return -log(y); // denormalized range, R change
if (y <= 10) return log(fabs(gammafn(x)));
/*
ELSE y = |x| > 10 ---------------------- */
if (y > xmax) {
throw("Argument too big");
return +INFINITY;
}
if (x > 0) { /* i.e. y = x > 10 */
#ifdef IEEE_754
if(x > 1e17)
return(x*(log(x) - 1.));
else if(x > 4934720.)
return(M_LN_SQRT_2PI + (x - 0.5) * log(x) - x);
else
#endif
return M_LN_SQRT_2PI + (x - 0.5) * log(x) - x + lgammacor(x);
}
/* else: x < -10; y = -x */
sinpiy = fabs(sinpi(y));
if (sinpiy == 0) { /* Negative integer argument ===
Now UNNECESSARY: caught above */
printf(" ** should NEVER happen! *** [lgamma.c: Neg.int, y=%g]\n",y);
return std::numeric_limits<double>::quiet_NaN();
}
ans = M_LN_SQRT_PId2 + (x - 0.5) * log(y) - x - log(sinpiy) - lgammacor(y);
if(fabs((x - trunc(x - 0.5)) * ans / x) < dxrel) {
/* The answer is less than half precision because
* the argument is too near a negative integer. */
throw("The answer is less than half precision because the argument is too near a negative integer");
}
return ans;
}
double lgammafn(double x)
{
return lgammafn_sign(x, NULL);
}
static double
logcf (double x, double i, double d,
double eps /* ~ relative tolerance */)
{
double c1 = 2 * d;
double c2 = i + d;
double c4 = c2 + d;
double a1 = c2;
double b1 = i * (c2 - i * x);
double b2 = d * d * x;
double a2 = c4 * c2 - b2;
#if 0
assert (i > 0);
assert (d >= 0);
#endif
b2 = c4 * b1 - i * b2;
while (fabs(a2 * b1 - a1 * b2) > fabs(eps * b1 * b2)) {
double c3 = c2*c2*x;
c2 += d;
c4 += d;
a1 = c4 * a2 - c3 * a1;
b1 = c4 * b2 - c3 * b1;
c3 = c1 * c1 * x;
c1 += d;
c4 += d;
a2 = c4 * a1 - c3 * a2;
b2 = c4 * b1 - c3 * b2;
if (fabs (b2) > scalefactor) {
a1 /= scalefactor;
b1 /= scalefactor;
a2 /= scalefactor;
b2 /= scalefactor;
} else if (fabs (b2) < 1 / scalefactor) {
a1 *= scalefactor;
b1 *= scalefactor;
a2 *= scalefactor;
b2 *= scalefactor;
}
}
return a2 / b2;
}
/* Accurate calculation of log(1+x)-x, particularly for small x. */
double log1pmx (double x)
{
static const double minLog1Value = -0.79149064;
if (x > 1 || x < minLog1Value)
return log1p(x) - x;
else { /* -.791 <= x <= 1 -- expand in [x/(2+x)]^2 =: y :
* log(1+x) - x = x/(2+x) * [ 2 * y * S(y) - x], with
* ---------------------------------------------
* S(y) = 1/3 + y/5 + y^2/7 + ... = \sum_{k=0}^\infty y^k / (2k + 3)
*/
double r = x / (2 + x), y = r * r;
if (fabs(x) < 1e-2) {
static const double two = 2;
return r * ((((two / 9 * y + two / 7) * y + two / 5) * y +
two / 3) * y - x);
} else {
static const double tol_logcf = 1e-14;
return r * (2 * y * logcf (y, 3, 2, tol_logcf) - x);
}
}
}
/* Compute log(gamma(a+1)) accurately also for small a (0 < a < 0.5). */
double lgamma1p (double a)
{
const double eulers_const = 0.5772156649015328606065120900824024;
/* coeffs[i] holds (zeta(i+2)-1)/(i+2) , i = 0:(N-1), N = 40 : */
const int N = 40;
static const double coeffs[40] = {
0.3224670334241132182362075833230126e-0,/* = (zeta(2)-1)/2 */
0.6735230105319809513324605383715000e-1,/* = (zeta(3)-1)/3 */
0.2058080842778454787900092413529198e-1,
0.7385551028673985266273097291406834e-2,
0.2890510330741523285752988298486755e-2,
0.1192753911703260977113935692828109e-2,
0.5096695247430424223356548135815582e-3,
0.2231547584535793797614188036013401e-3,
0.9945751278180853371459589003190170e-4,
0.4492623673813314170020750240635786e-4,
0.2050721277567069155316650397830591e-4,
0.9439488275268395903987425104415055e-5,
0.4374866789907487804181793223952411e-5,
0.2039215753801366236781900709670839e-5,
0.9551412130407419832857179772951265e-6,
0.4492469198764566043294290331193655e-6,
0.2120718480555466586923135901077628e-6,
0.1004322482396809960872083050053344e-6,
0.4769810169363980565760193417246730e-7,
0.2271109460894316491031998116062124e-7,
0.1083865921489695409107491757968159e-7,
0.5183475041970046655121248647057669e-8,
0.2483674543802478317185008663991718e-8,
0.1192140140586091207442548202774640e-8,
0.5731367241678862013330194857961011e-9,
0.2759522885124233145178149692816341e-9,
0.1330476437424448948149715720858008e-9,
0.6422964563838100022082448087644648e-10,
0.3104424774732227276239215783404066e-10,
0.1502138408075414217093301048780668e-10,
0.7275974480239079662504549924814047e-11,
0.3527742476575915083615072228655483e-11,
0.1711991790559617908601084114443031e-11,
0.8315385841420284819798357793954418e-12,
0.4042200525289440065536008957032895e-12,
0.1966475631096616490411045679010286e-12,
0.9573630387838555763782200936508615e-13,
0.4664076026428374224576492565974577e-13,
0.2273736960065972320633279596737272e-13,
0.1109139947083452201658320007192334e-13/* = (zeta(40+1)-1)/(40+1) */
};
const double c = 0.2273736845824652515226821577978691e-12;/* zeta(N+2)-1 */
const double tol_logcf = 1e-14;
double lgam;
int i;
if (fabs (a) >= 0.5)
return lgammafn (a + 1);
/* Abramowitz & Stegun 6.1.33 : for |x| < 2,
* <==> log(gamma(1+x)) = -(log(1+x) - x) - gamma*x + x^2 * \sum_{n=0}^\infty c_n (-x)^n
* where c_n := (Zeta(n+2) - 1)/(n+2) = coeffs[n]
*
* Here, another convergence acceleration trick is used to compute
* lgam(x) := sum_{n=0..Inf} c_n (-x)^n
*/
lgam = c * logcf(-a / 2, N + 2, 1, tol_logcf);
for (i = N - 1; i >= 0; i--)
lgam = coeffs[i] - a * lgam;
return (a * lgam - eulers_const) * a - log1pmx (a);
} /* lgamma1p */
double fmax2(double x, double y)
{
#ifdef IEEE_754
if (ISNAN(x) || ISNAN(y))
return x + y;
#endif
return (x < y) ? y : x;
}
/*
* Compute the log of a sum from logs of terms, i.e.,
*
* log (exp (logx) + exp (logy))
*
* without causing overflows and without throwing away large handfuls
* of accuracy.
*/
double logspace_add (double logx, double logy)
{
return fmax2 (logx, logy) + log1p (exp (-fabs (logx - logy)));
}
/*
* Compute the log of a difference from logs of terms, i.e.,
*
* log (exp (logx) - exp (logy))
*
* without causing overflows and without throwing away large handfuls
* of accuracy.
*/
double logspace_sub (double logx, double logy)
{
return logx + R_Log1_Exp(logy - logx);
}
/*
* Compute the log of a sum from logs of terms, i.e.,
*
* log (sum_i exp (logx[i]) ) =
* log (e^M * sum_i e^(logx[i] - M) ) =
* M + log( sum_i e^(logx[i] - M)
*
* without causing overflows or throwing much accuracy.
*/
#ifdef HAVE_LONG_DOUBLE
# define EXP expl
# define LOG logl
#else
# define EXP exp
# define LOG log
#endif
double logspace_sum (const double* logx, int n)
{
if(n == 0) return 0; // = log( sum(<empty>) )
if(n == 1) return logx[0];
if(n == 2) return logspace_add(logx[0], logx[1]);
// else (n >= 3) :
int i;
// Mx := max_i log(x_i)
double Mx = logx[0];
for(i = 1; i < n; i++) if(Mx < logx[i]) Mx = logx[i];
LDOUBLE s = (LDOUBLE) 0.;
for(i = 0; i < n; i++) s += EXP(logx[i] - Mx);
return Mx + (double) LOG(s);
}
double attribute_hidden bd0(double x, double np)
{
double ej, s, s1, v;
int j;
if(isinf(x) || isinf(np) || np == 0.0) return std::numeric_limits<double>::quiet_NaN();
if (fabs(x-np) < 0.1*(x+np)) {
v = (x-np)/(x+np); // might underflow to 0
s = (x-np)*v;/* s using v -- change by MM */
if(fabs(s) < DBL_MIN) return s;
ej = 2*x*v;
v = v*v;
for (j = 1; j < 1000; j++) { /* Taylor series; 1000: no infinite loop
as |v| < .1, v^2000 is "zero" */
ej *= v;// = v^(2j+1)
s1 = s+ej/((j<<1)+1);
if (s1 == s) /* last term was effectively 0 */
return s1 ;
s = s1;
}
}
/* else: | x - np | is not too small */
return(x*log(x/np)+np-x);
}
double dpois_raw(double x, double lambda, int give_log)
{
/* x >= 0 ; integer for dpois(), but not e.g. for pgamma()!
lambda >= 0
*/
if (lambda == 0) return( (x == 0) ? R_D__1 : R_D__0 );
if (isinf(lambda)) return R_D__0;
if (x < 0) return( R_D__0 );
if (x <= lambda * DBL_MIN) return(R_D_exp(-lambda) );
if (lambda < x * DBL_MIN) return(R_D_exp(-lambda + x*log(lambda) -lgammafn(x+1)));
return(R_D_fexp( M_2PI*x, -stirlerr(x)-bd0(x,lambda) ));
}
/* dpois_wrap (x__1, lambda) := dpois(x__1 - 1, lambda); where
* dpois(k, L) := exp(-L) L^k / gamma(k+1) {the usual Poisson probabilities}
*
* and dpois*(.., give_log = TRUE) := log( dpois*(..) )
*/
static double
dpois_wrap (double x_plus_1, double lambda, int give_log)
{
#ifdef DEBUG_p
REprintf (" dpois_wrap(x+1=%.14g, lambda=%.14g, log=%d)\n",
x_plus_1, lambda, give_log);
#endif
if (isinf(lambda))
return 0;
if (x_plus_1 > 1)
return dpois_raw (x_plus_1 - 1, lambda, give_log);
if (lambda > fabs(x_plus_1 - 1) * M_cutoff)
return R_D_exp(-lambda - lgammafn(x_plus_1));
else {
double d = dpois_raw (x_plus_1, lambda, give_log);
#ifdef DEBUG_p
REprintf (" -> d=dpois_raw(..)=%.14g\n", d);
#endif
return give_log
? d + log (x_plus_1 / lambda)
: d * (x_plus_1 / lambda);
}
}
/*
* Abramowitz and Stegun 6.5.29 [right]
*/
static double
pgamma_smallx (double x, double alph, int lower_tail, int log_p)
{
double sum = 0, c = alph, n = 0, term;
#ifdef DEBUG_p
REprintf (" pg_smallx(x=%.12g, alph=%.12g): ", x, alph);
#endif
/*
* Relative to 6.5.29 all terms have been multiplied by alph
* and the first, thus being 1, is omitted.
*/
do {
n++;
c *= -x / n;
term = c / (alph + n);
sum += term;
} while (fabs (term) > DBL_EPSILON * fabs (sum));
#ifdef DEBUG_p
REprintf ("%5.0f terms --> conv.sum=%g;", n, sum);
#endif
if (lower_tail) {
double f1 = log_p ? log1p (sum) : 1 + sum;
double f2;
if (alph > 1) {
f2 = dpois_raw (alph, x, log_p);
f2 = log_p ? f2 + x : f2 * exp (x);
} else if (log_p)
f2 = alph * log (x) - lgamma1p (alph);
else
f2 = pow (x, alph) / exp (lgamma1p (alph));
#ifdef DEBUG_p
REprintf (" (f1,f2)= (%g,%g)\n", f1,f2);
#endif
return log_p ? f1 + f2 : f1 * f2;
} else {
double lf2 = alph * log (x) - lgamma1p (alph);
#ifdef DEBUG_p
REprintf (" 1:%.14g 2:%.14g\n", alph * log (x), lgamma1p (alph));
REprintf (" sum=%.14g log(1+sum)=%.14g lf2=%.14g\n",
sum, log1p (sum), lf2);
#endif
if (log_p)
return R_Log1_Exp (log1p (sum) + lf2);
else {
double f1m1 = sum;
double f2m1 = expm1 (lf2);
return -(f1m1 + f2m1 + f1m1 * f2m1);
}
}
} /* pgamma_smallx() */
static double
pd_upper_series (double x, double y, int log_p)
{
double term = x / y;
double sum = term;
do {
y++;
term *= x / y;
sum += term;
} while (term > sum * DBL_EPSILON);
/* sum = \sum_{n=1}^ oo x^n / (y*(y+1)*...*(y+n-1))
* = \sum_{n=0}^ oo x^(n+1) / (y*(y+1)*...*(y+n))
* = x/y * (1 + \sum_{n=1}^oo x^n / ((y+1)*...*(y+n)))
* ~ x/y + o(x/y) {which happens when alph -> Inf}
*/
return log_p ? log (sum) : sum;
}
/* Continued fraction for calculation of
* scaled upper-tail F_{gamma}
* ~= (y / d) * [1 + (1-y)/d + O( ((1-y)/d)^2 ) ]
*/
static double
pd_lower_cf (double y, double d)
{
double f= 0.0 /* -Wall */, of, f0;
double i, c2, c3, c4, a1, b1, a2, b2;
#define NEEDED_SCALE \
(b2 > scalefactor) { \
a1 /= scalefactor; \
b1 /= scalefactor; \
a2 /= scalefactor; \
b2 /= scalefactor; \
}
#define max_it 200000
#ifdef DEBUG_p
REprintf("pd_lower_cf(y=%.14g, d=%.14g)", y, d);
#endif
if (y == 0) return 0;
f0 = y/d;
/* Needed, e.g. for pgamma(10^c(100,295), shape= 1.1, log=TRUE): */
if(fabs(y - 1) < fabs(d) * DBL_EPSILON) { /* includes y < d = Inf */
#ifdef DEBUG_p
REprintf(" very small 'y' -> returning (y/d)\n");
#endif
return (f0);
}
if(f0 > 1.) f0 = 1.;
c2 = y;
c4 = d; /* original (y,d), *not* potentially scaled ones!*/
a1 = 0; b1 = 1;
a2 = y; b2 = d;
while NEEDED_SCALE
i = 0; of = -1.; /* far away */
while (i < max_it) {
i++; c2--; c3 = i * c2; c4 += 2;
/* c2 = y - i, c3 = i(y - i), c4 = d + 2i, for i odd */
a1 = c4 * a2 + c3 * a1;
b1 = c4 * b2 + c3 * b1;
i++; c2--; c3 = i * c2; c4 += 2;