forked from synalp/NER
-
Notifications
You must be signed in to change notification settings - Fork 0
/
samplib.c
2657 lines (2550 loc) · 80.3 KB
/
samplib.c
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
#define _GNU_SOURCE
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include "samplib.h"
/* Logarithm of the gamma function.
References:
1) W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for
the Natural Logarithm of the Gamma Function,' Math. Comp. 21,
1967, pp. 198-203.
2) K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May,
1969.
3) Hart, Et. Al., Computer Approximations, Wiley and sons, New
York, 1968.
From matlab/gammaln.m
*/
double gammaln(double x)
{
double result, y, xnum, xden;
int i;
static double d1 = -5.772156649015328605195174e-1;
static double p1[] = {
4.945235359296727046734888e0, 2.018112620856775083915565e2,
2.290838373831346393026739e3, 1.131967205903380828685045e4,
2.855724635671635335736389e4, 3.848496228443793359990269e4,
2.637748787624195437963534e4, 7.225813979700288197698961e3
};
static double q1[] = {
6.748212550303777196073036e1, 1.113332393857199323513008e3,
7.738757056935398733233834e3, 2.763987074403340708898585e4,
5.499310206226157329794414e4, 6.161122180066002127833352e4,
3.635127591501940507276287e4, 8.785536302431013170870835e3
};
static double d2 = 4.227843350984671393993777e-1;
static double p2[] = {
4.974607845568932035012064e0, 5.424138599891070494101986e2,
1.550693864978364947665077e4, 1.847932904445632425417223e5,
1.088204769468828767498470e6, 3.338152967987029735917223e6,
5.106661678927352456275255e6, 3.074109054850539556250927e6
};
static double q2[] = {
1.830328399370592604055942e2, 7.765049321445005871323047e3,
1.331903827966074194402448e5, 1.136705821321969608938755e6,
5.267964117437946917577538e6, 1.346701454311101692290052e7,
1.782736530353274213975932e7, 9.533095591844353613395747e6
};
static double d4 = 1.791759469228055000094023e0;
static double p4[] = {
1.474502166059939948905062e4, 2.426813369486704502836312e6,
1.214755574045093227939592e8, 2.663432449630976949898078e9,
2.940378956634553899906876e10, 1.702665737765398868392998e11,
4.926125793377430887588120e11, 5.606251856223951465078242e11
};
static double q4[] = {
2.690530175870899333379843e3, 6.393885654300092398984238e5,
4.135599930241388052042842e7, 1.120872109616147941376570e9,
1.488613728678813811542398e10, 1.016803586272438228077304e11,
3.417476345507377132798597e11, 4.463158187419713286462081e11
};
static double c[] = {
-1.910444077728e-03, 8.4171387781295e-04,
-5.952379913043012e-04, 7.93650793500350248e-04,
-2.777777777777681622553e-03, 8.333333333333333331554247e-02,
5.7083835261e-03
};
static double a = 0.6796875;
if((x <= 0.5) || ((x > a) && (x <= 1.5))) {
if(x <= 0.5) {
result = -log(x);
/* Test whether X < machine epsilon. */
if(x+1 == 1) {
return result;
}
}
else {
result = 0;
x = (x - 0.5) - 0.5;
}
xnum = 0;
xden = 1;
for(i=0;i<8;i++) {
xnum = xnum * x + p1[i];
xden = xden * x + q1[i];
}
result += x*(d1 + x*(xnum/xden));
}
else if((x <= a) || ((x > 1.5) && (x <= 4))) {
if(x <= a) {
result = -log(x);
x = (x - 0.5) - 0.5;
}
else {
result = 0;
x -= 2;
}
xnum = 0;
xden = 1;
for(i=0;i<8;i++) {
xnum = xnum * x + p2[i];
xden = xden * x + q2[i];
}
result += x*(d2 + x*(xnum/xden));
}
else if(x <= 12) {
x -= 4;
xnum = 0;
xden = -1;
for(i=0;i<8;i++) {
xnum = xnum * x + p4[i];
xden = xden * x + q4[i];
}
result = d4 + x*(xnum/xden);
}
/* X > 12 */
else {
y = log(x);
result = x*(y - 1) - y*0.5 + .9189385332046727417803297;
x = 1/x;
y = x*x;
xnum = c[6];
for(i=0;i<6;i++) {
xnum = xnum * y + c[i];
}
xnum *= x;
result += xnum;
}
return result;
}
/* The digamma function is the derivative of gammaln.
Reference:
J Bernardo,
Psi ( Digamma ) Function,
Algorithm AS 103,
Applied Statistics,
Volume 25, Number 3, pages 315-317, 1976.
From http://www.psc.edu/~burkardt/src/dirichlet/dirichlet.f
(with modifications for negative numbers and extra precision)
*/
double digamma(double x)
{
static const double
c = 12,
d1 = -0.57721566490153286,
d2 = 1.6449340668482264365, /* pi^2/6 */
s = 1e-6,
s3 = 1./12,
s4 = 1./120,
s5 = 1./252,
s6 = 1./240,
s7 = 1./132,
s8 = 691/32760,
s9 = 1/12,
s10 = 3617/8160;
double result;
#if 0
static double cache_x = 0;
static int hits = 0, total = 0;
total++;
if(x == cache_x) {
hits++;
}
if(total % 1000 == 1) {
printf("hits = %d, total = %d, hits/total = %g\n", hits, total,
((double)hits)/total);
}
cache_x = x;
#endif
/* Illegal arguments */
if((isinf(x) == -1) || isnan(x)) {
return NAN;
}
/* Singularities */
if((x <= 0) && (floor(x) == x)) {
return -INFINITY;
}
/* Negative values */
/* Use the reflection formula (Jeffrey 11.1.6):
* digamma(-x) = digamma(x+1) + pi*cot(pi*x)
*
* This is related to the identity
* digamma(-x) = digamma(x+1) - digamma(z) + digamma(1-z)
* where z is the fractional part of x
* For example:
* digamma(-3.1) = 1/3.1 + 1/2.1 + 1/1.1 + 1/0.1 + digamma(1-0.1)
* = digamma(4.1) - digamma(0.1) + digamma(1-0.1)
* Then we use
* digamma(1-z) - digamma(z) = pi*cot(pi*z)
*/
if(x < 0) {
return digamma(1-x) + 3.14159265/tan(-3.14159265*x);
}
/* Use Taylor series if argument <= S */
if(x <= s) return d1 - 1/x + d2*x;
/* Reduce to digamma(X + N) where (X + N) >= C */
result = 0;
while(x < c) {
result -= 1/x;
x++;
}
/* Use de Moivre's expansion if argument >= C */
/* This expansion can be computed in Maple via asympt(Psi(x),x) */
if(x >= c) {
double r = 1/x;
result += log(x) - 0.5*r;
r *= r;
result -= r * (s3 - r * (s4 - r * (s5 - r * (s6 - r * s7))));
}
return result;
}
/* The trigamma function is the derivative of the digamma function.
Reference:
B Schneider,
Trigamma Function,
Algorithm AS 121,
Applied Statistics,
Volume 27, Number 1, page 97-99, 1978.
From http://www.psc.edu/~burkardt/src/dirichlet/dirichlet.f
(with modification for negative arguments and extra precision)
*/
double trigamma(double x)
{
double
small = 1e-4,
large = 8,
c = 1.6449340668482264365, /* pi^2/6 = Zeta(2) */
c1 = -2.404113806319188570799476, /* -2 Zeta(3) */
b2 = 1./6,
b4 = -1./30,
b6 = 1./42,
b8 = -1./30,
b10 = 5./66;
double result;
/* Illegal arguments */
if((isinf(x) == -1) || isnan(x)) {
return NAN;
}
/* Singularities */
if((x <= 0) && (floor(x) == x)) {
return -INFINITY;
}
/* Negative values */
/* Use the derivative of the digamma reflection formula:
* -trigamma(-x) = trigamma(x+1) - (pi*csc(pi*x))^2
*/
if(x < 0) {
result = M_PI/sin(-M_PI*x);
return -trigamma(1-x) + result*result;
}
/* Use Taylor series if argument <= small */
if(x <= small) {
return 1/(x*x) + c + c1*x;
}
result = 0;
/* Reduce to trigamma(x+n) where ( X + N ) >= B */
while(x < large) {
result += 1/(x*x);
x++;
}
/* Apply asymptotic formula when X >= B */
/* This expansion can be computed in Maple via asympt(Psi(1,x),x) */
if(x >= large) {
double r = 1/(x*x);
result += 0.5*r + (1 + r*(b2 + r*(b4 + r*(b6 + r*(b8 + r*b10)))))/x;
}
return result;
}
double invdigamma(double y) {
double x = (y <= -2.22) ? (-1 / (y + 0.5772156649015353)) : (exp(y) + 0.5);
/* never need more than 5 iterations; we unfold them ourselves */
x = x - (digamma(x) - y) / trigamma(x);
x = x - (digamma(x) - y) / trigamma(x);
x = x - (digamma(x) - y) / trigamma(x);
x = x - (digamma(x) - y) / trigamma(x);
x = x - (digamma(x) - y) / trigamma(x);
return x;
}
#define ABS(x) ((x) >= 0 ? (x) : -(x))
#define min(a,b) ((a) <= (b) ? (a) : (b))
#define max(a,b) ((a) >= (b) ? (a) : (b))
void ftnstop(char*);
double genbet(double aa,double bb)
/*
**********************************************************************
double genbet(double aa,double bb)
GeNerate BETa random deviate
Function
Returns a single random deviate from the beta distribution with
parameters A and B. The density of the beta is
x^(a-1) * (1-x)^(b-1) / B(a,b) for 0 < x < 1
Arguments
aa --> First parameter of the beta distribution
bb --> Second parameter of the beta distribution
Method
R. C. H. Cheng
Generating Beta Variatew with Nonintegral Shape Parameters
Communications of the ACM, 21:317-322 (1978)
(Algorithms BB and BC)
**********************************************************************
*/
{
#define expmax 89.0
#define infnty 1.0E38
static double olda = -1.0;
static double oldb = -1.0;
static double genbet,a,alpha,b,beta,delta,gamma,k1,k2,r,s,t,u1,u2,v,w,y,z;
static long qsame;
qsame = olda == aa && oldb == bb;
if(qsame) goto S20;
if(!(aa <= 0.0 || bb <= 0.0)) goto S10;
fputs(" AA or BB <= 0 in GENBET - Abort!",stderr);
fprintf(stderr," AA: %16.6E BB %16.6E\n",aa,bb);
exit(1);
S10:
olda = aa;
oldb = bb;
S20:
if(!(min(aa,bb) > 1.0)) goto S100;
/*
Alborithm BB
Initialize
*/
if(qsame) goto S30;
a = min(aa,bb);
b = max(aa,bb);
alpha = a+b;
beta = sqrt((alpha-2.0)/(2.0*a*b-alpha));
gamma = a+1.0/beta;
S30:
S40:
u1 = ranf();
/*
Step 1
*/
u2 = ranf();
v = beta*log(u1/(1.0-u1));
if(!(v > expmax)) goto S50;
w = infnty;
goto S60;
S50:
w = a*exp(v);
S60:
z = pow(u1,2.0)*u2;
r = gamma*v-1.3862944;
s = a+r-w;
/*
Step 2
*/
if(s+2.609438 >= 5.0*z) goto S70;
/*
Step 3
*/
t = log(z);
if(s > t) goto S70;
/*
Step 4
*/
if(r+alpha*log(alpha/(b+w)) < t) goto S40;
S70:
/*
Step 5
*/
if(!(aa == a)) goto S80;
genbet = w/(b+w);
goto S90;
S80:
genbet = b/(b+w);
S90:
goto S230;
S100:
/*
Algorithm BC
Initialize
*/
if(qsame) goto S110;
a = max(aa,bb);
b = min(aa,bb);
alpha = a+b;
beta = 1.0/b;
delta = 1.0+a-b;
k1 = delta*(1.38889E-2+4.16667E-2*b)/(a*beta-0.777778);
k2 = 0.25+(0.5+0.25/delta)*b;
S110:
S120:
u1 = ranf();
/*
Step 1
*/
u2 = ranf();
if(u1 >= 0.5) goto S130;
/*
Step 2
*/
y = u1*u2;
z = u1*y;
if(0.25*u2+z-y >= k1) goto S120;
goto S170;
S130:
/*
Step 3
*/
z = pow(u1,2.0)*u2;
if(!(z <= 0.25)) goto S160;
v = beta*log(u1/(1.0-u1));
if(!(v > expmax)) goto S140;
w = infnty;
goto S150;
S140:
w = a*exp(v);
S150:
goto S200;
S160:
if(z >= k2) goto S120;
S170:
/*
Step 4
Step 5
*/
v = beta*log(u1/(1.0-u1));
if(!(v > expmax)) goto S180;
w = infnty;
goto S190;
S180:
w = a*exp(v);
S190:
if(alpha*(log(alpha/(b+w))+v)-1.3862944 < log(z)) goto S120;
S200:
/*
Step 6
*/
if(!(a == aa)) goto S210;
genbet = w/(b+w);
goto S220;
S210:
genbet = b/(b+w);
S230:
S220:
return genbet;
#undef expmax
#undef infnty
}
double genchi(double df)
/*
**********************************************************************
double genchi(double df)
Generate random value of CHIsquare variable
Function
Generates random deviate from the distribution of a chisquare
with DF degrees of freedom random variable.
Arguments
df --> Degrees of freedom of the chisquare
(Must be positive)
Method
Uses relation between chisquare and gamma.
**********************************************************************
*/
{
static double genchi;
if(!(df <= 0.0)) goto S10;
fputs("DF <= 0 in GENCHI - ABORT",stderr);
fprintf(stderr,"Value of DF: %16.6E\n",df);
exit(1);
S10:
genchi = 2.0*gengam(1.0,df/2.0);
return genchi;
}
double genexp(double av)
/*
**********************************************************************
double genexp(double av)
GENerate EXPonential random deviate
Function
Generates a single random deviate from an exponential
distribution with mean AV.
Arguments
av --> The mean of the exponential distribution from which
a random deviate is to be generated.
Method
Renames SEXPO from TOMS as slightly modified by BWB to use RANF
instead of SUNIF.
For details see:
Ahrens, J.H. and Dieter, U.
Computer Methods for Sampling From the
Exponential and Normal Distributions.
Comm. ACM, 15,10 (Oct. 1972), 873 - 882.
**********************************************************************
*/
{
static double genexp;
genexp = sexpo()*av;
return genexp;
}
double genf(double dfn,double dfd)
/*
**********************************************************************
double genf(double dfn,double dfd)
GENerate random deviate from the F distribution
Function
Generates a random deviate from the F (variance ratio)
distribution with DFN degrees of freedom in the numerator
and DFD degrees of freedom in the denominator.
Arguments
dfn --> Numerator degrees of freedom
(Must be positive)
dfd --> Denominator degrees of freedom
(Must be positive)
Method
Directly generates ratio of chisquare variates
**********************************************************************
*/
{
static double genf,xden,xnum;
if(!(dfn <= 0.0 || dfd <= 0.0)) goto S10;
fputs("Degrees of freedom nonpositive in GENF - abort!",stderr);
fprintf(stderr,"DFN value: %16.6EDFD value: %16.6E\n",dfn,dfd);
exit(1);
S10:
xnum = genchi(dfn)/dfn;
/*
GENF = ( GENCHI( DFN ) / DFN ) / ( GENCHI( DFD ) / DFD )
*/
xden = genchi(dfd)/dfd;
if(!(xden <= 9.999999999998E-39*xnum)) goto S20;
fputs(" GENF - generated numbers would cause overflow",stderr);
fprintf(stderr," Numerator %16.6E Denominator %16.6E\n",xnum,xden);
fputs(" GENF returning 1.0E38",stderr);
genf = 1.0E38;
goto S30;
S20:
genf = xnum/xden;
S30:
return genf;
}
double gengam(double a,double r)
/*
**********************************************************************
double gengam(double a,double r)
GENerates random deviates from GAMma distribution
Function
Generates random deviates from the gamma distribution whose
density is
(A**R)/Gamma(R) * X**(R-1) * Exp(-A*X)
Arguments
a --> Location parameter of Gamma distribution
r --> Shape parameter of Gamma distribution
Method
Renames SGAMMA from TOMS as slightly modified by BWB to use RANF
instead of SUNIF.
For details see:
(Case R >= 1.0)
Ahrens, J.H. and Dieter, U.
Generating Gamma Variates by a
Modified Rejection Technique.
Comm. ACM, 25,1 (Jan. 1982), 47 - 54.
Algorithm GD
(Case 0.0 <= R <= 1.0)
Ahrens, J.H. and Dieter, U.
Computer Methods for Sampling from Gamma,
Beta, Poisson and Binomial Distributions.
Computing, 12 (1974), 223-246/
Adapted algorithm GS.
**********************************************************************
*/
{
static double gengam;
gengam = sgamma(r);
gengam /= a;
return gengam;
}
void genmn(double *parm,double *x,double *work)
/*
**********************************************************************
void genmn(double *parm,double *x,double *work)
GENerate Multivariate Normal random deviate
Arguments
parm --> Parameters needed to generate multivariate normal
deviates (MEANV and Cholesky decomposition of
COVM). Set by a previous call to SETGMN.
1 : 1 - size of deviate, P
2 : P + 1 - mean vector
P+2 : P*(P+3)/2 + 1 - upper half of cholesky
decomposition of cov matrix
x <-- Vector deviate generated.
work <--> Scratch array
Method
1) Generate P independent standard normal deviates - Ei ~ N(0,1)
2) Using Cholesky decomposition find A s.t. trans(A)*A = COVM
3) trans(A)E + MEANV ~ N(MEANV,COVM)
**********************************************************************
*/
{
static long i,icount,j,p,D1,D2,D3,D4;
static double ae;
p = (long) (*parm);
/*
Generate P independent normal deviates - WORK ~ N(0,1)
*/
for(i=1; i<=p; i++) *(work+i-1) = snorm();
for(i=1,D3=1,D4=(p-i+D3)/D3; D4>0; D4--,i+=D3) {
/*
PARM (P+2 : P*(P+3)/2 + 1) contains A, the Cholesky
decomposition of the desired covariance matrix.
trans(A)(1,1) = PARM(P+2)
trans(A)(2,1) = PARM(P+3)
trans(A)(2,2) = PARM(P+2+P)
trans(A)(3,1) = PARM(P+4)
trans(A)(3,2) = PARM(P+3+P)
trans(A)(3,3) = PARM(P+2-1+2P) ...
trans(A)*WORK + MEANV ~ N(MEANV,COVM)
*/
icount = 0;
ae = 0.0;
for(j=1,D1=1,D2=(i-j+D1)/D1; D2>0; D2--,j+=D1) {
icount += (j-1);
ae += (*(parm+i+(j-1)*p-icount+p)**(work+j-1));
}
*(x+i-1) = ae+*(parm+i);
}
}
void genmul(long n,double *p,long ncat,long *ix)
/*
**********************************************************************
void genmul(int n,double *p,int ncat,int *ix)
GENerate an observation from the MULtinomial distribution
Arguments
N --> Number of events that will be classified into one of
the categories 1..NCAT
P --> Vector of probabilities. P(i) is the probability that
an event will be classified into category i. Thus, P(i)
must be [0,1]. Only the first NCAT-1 P(i) must be defined
since P(NCAT) is 1.0 minus the sum of the first
NCAT-1 P(i).
NCAT --> Number of categories. Length of P and IX.
IX <-- Observation from multinomial distribution. All IX(i)
will be nonnegative and their sum will be N.
Method
Algorithm from page 559 of
Devroye, Luc
Non-Uniform Random Variate Generation. Springer-Verlag,
New York, 1986.
**********************************************************************
*/
{
static double prob,ptot,sum;
static long i,icat,ntot;
if(n < 0) ftnstop("N < 0 in GENMUL");
if(ncat <= 1) ftnstop("NCAT <= 1 in GENMUL");
ptot = 0.0F;
for(i=0; i<ncat-1; i++) {
if(*(p+i) < 0.0F) ftnstop("Some P(i) < 0 in GENMUL");
if(*(p+i) > 1.0F) ftnstop("Some P(i) > 1 in GENMUL");
ptot += *(p+i);
}
if(ptot > 0.99999F) ftnstop("Sum of P(i) > 1 in GENMUL");
/*
Initialize variables
*/
ntot = n;
sum = 1.0F;
for(i=0; i<ncat; i++) ix[i] = 0;
/*
Generate the observation
*/
for(icat=0; icat<ncat-1; icat++) {
prob = *(p+icat)/sum;
*(ix+icat) = ignbin(ntot,prob);
ntot -= *(ix+icat);
if(ntot <= 0) return;
sum -= *(p+icat);
}
*(ix+ncat-1) = ntot;
/*
Finished
*/
return;
}
double gennch(double df,double xnonc)
/*
**********************************************************************
double gennch(double df,double xnonc)
Generate random value of Noncentral CHIsquare variable
Function
Generates random deviate from the distribution of a noncentral
chisquare with DF degrees of freedom and noncentrality parameter
xnonc.
Arguments
df --> Degrees of freedom of the chisquare
(Must be > 1.0)
xnonc --> Noncentrality parameter of the chisquare
(Must be >= 0.0)
Method
Uses fact that noncentral chisquare is the sum of a chisquare
deviate with DF-1 degrees of freedom plus the square of a normal
deviate with mean XNONC and standard deviation 1.
**********************************************************************
*/
{
static double gennch;
if(!(df <= 1.0 || xnonc < 0.0)) goto S10;
fputs("DF <= 1 or XNONC < 0 in GENNCH - ABORT",stderr);
fprintf(stderr,"Value of DF: %16.6E Value of XNONC%16.6E\n",df,xnonc);
exit(1);
S10:
gennch = genchi(df-1.0)+pow(gennor(sqrt(xnonc),1.0),2.0);
return gennch;
}
double gennf(double dfn,double dfd,double xnonc)
/*
**********************************************************************
double gennf(double dfn,double dfd,double xnonc)
GENerate random deviate from the Noncentral F distribution
Function
Generates a random deviate from the noncentral F (variance ratio)
distribution with DFN degrees of freedom in the numerator, and DFD
degrees of freedom in the denominator, and noncentrality parameter
XNONC.
Arguments
dfn --> Numerator degrees of freedom
(Must be >= 1.0)
dfd --> Denominator degrees of freedom
(Must be positive)
xnonc --> Noncentrality parameter
(Must be nonnegative)
Method
Directly generates ratio of noncentral numerator chisquare variate
to central denominator chisquare variate.
**********************************************************************
*/
{
static double gennf,xden,xnum;
static long qcond;
qcond = dfn <= 1.0 || dfd <= 0.0 || xnonc < 0.0;
if(!qcond) goto S10;
fputs("In GENNF - Either (1) Numerator DF <= 1.0 or",stderr);
fputs("(2) Denominator DF < 0.0 or ",stderr);
fputs("(3) Noncentrality parameter < 0.0",stderr);
fprintf(stderr,
"DFN value: %16.6EDFD value: %16.6EXNONC value: \n%16.6E\n",dfn,dfd,
xnonc);
exit(1);
S10:
xnum = gennch(dfn,xnonc)/dfn;
/*
GENNF = ( GENNCH( DFN, XNONC ) / DFN ) / ( GENCHI( DFD ) / DFD )
*/
xden = genchi(dfd)/dfd;
if(!(xden <= 9.999999999998E-39*xnum)) goto S20;
fputs(" GENNF - generated numbers would cause overflow",stderr);
fprintf(stderr," Numerator %16.6E Denominator %16.6E\n",xnum,xden);
fputs(" GENNF returning 1.0E38",stderr);
gennf = 1.0E38;
goto S30;
S20:
gennf = xnum/xden;
S30:
return gennf;
}
double gennor(double av,double sd)
/*
**********************************************************************
double gennor(double av,double sd)
GENerate random deviate from a NORmal distribution
Function
Generates a single random deviate from a normal distribution
with mean, AV, and standard deviation, SD.
Arguments
av --> Mean of the normal distribution.
sd --> Standard deviation of the normal distribution.
Method
Renames SNORM from TOMS as slightly modified by BWB to use RANF
instead of SUNIF.
For details see:
Ahrens, J.H. and Dieter, U.
Extensions of Forsythe's Method for Random
Sampling from the Normal Distribution.
Math. Comput., 27,124 (Oct. 1973), 927 - 937.
**********************************************************************
*/
{
static double gennor;
gennor = sd*snorm()+av;
return gennor;
}
void genprm(long *iarray,int larray)
/*
**********************************************************************
void genprm(long *iarray,int larray)
GENerate random PeRMutation of iarray
Arguments
iarray <--> On output IARRAY is a random permutation of its
value on input
larray <--> Length of IARRAY
**********************************************************************
*/
{
static long i,itmp,iwhich,D1,D2;
for(i=1,D1=1,D2=(larray-i+D1)/D1; D2>0; D2--,i+=D1) {
iwhich = ignuin(i,larray);
itmp = *(iarray+iwhich-1);
*(iarray+iwhich-1) = *(iarray+i-1);
*(iarray+i-1) = itmp;
}
}
double genunf(double low,double high)
/*
**********************************************************************
double genunf(double low,double high)
GeNerate Uniform Real between LOW and HIGH
Function
Generates a real uniformly distributed between LOW and HIGH.
Arguments
low --> Low bound (exclusive) on real value to be generated
high --> High bound (exclusive) on real value to be generated
**********************************************************************
*/
{
static double genunf;
if(!(low > high)) goto S10;
fprintf(stderr,"LOW > HIGH in GENUNF: LOW %16.6E HIGH: %16.6E\n",low,high);
fputs("Abort",stderr);
exit(1);
S10:
genunf = low+(high-low)*ranf();
return genunf;
}
void gscgn(long getset,long *g)
/*
**********************************************************************
void gscgn(long getset,long *g)
Get/Set GeNerator
Gets or returns in G the number of the current generator
Arguments
getset --> 0 Get
1 Set
g <-- Number of the current random number generator (1..32)
**********************************************************************
*/
{
#define numg 32L
static long curntg = 1;
if(getset == 0) *g = curntg;
else {
if(*g < 0 || *g > numg) {
fputs(" Generator number out of range in GSCGN",stderr);
exit(0);
}
curntg = *g;
}
#undef numg
}
void gsrgs(long getset,long *qvalue)
/*
**********************************************************************
void gsrgs(long getset,long *qvalue)
Get/Set Random Generators Set
Gets or sets whether random generators set (initialized).
Initially (data statement) state is not set
If getset is 1 state is set to qvalue
If getset is 0 state returned in qvalue
**********************************************************************
*/
{
static long qinit = 0;
if(getset == 0) *qvalue = qinit;
else qinit = *qvalue;
}
void gssst(long getset,long *qset)
/*
**********************************************************************
void gssst(long getset,long *qset)
Get or Set whether Seed is Set
Initialize to Seed not Set
If getset is 1 sets state to Seed Set
If getset is 0 returns T in qset if Seed Set
Else returns F in qset
**********************************************************************
*/
{
static long qstate = 0;
if(getset != 0) qstate = 1;
else *qset = qstate;
}
long ignbin(long n,double pp)
/*
**********************************************************************
long ignbin(long n,double pp)
GENerate BINomial random deviate
Function
Generates a single random deviate from a binomial
distribution whose number of trials is N and whose
probability of an event in each trial is P.
Arguments
n --> The number of trials in the binomial distribution
from which a random deviate is to be generated.
p --> The probability of an event in each trial of the
binomial distribution from which a random deviate
is to be generated.
ignbin <-- A random deviate yielding the number of events
from N independent trials, each of which has
a probability of event P.
Method
This is algorithm BTPE from:
Kachitvichyanukul, V. and Schmeiser, B. W.
Binomial Random Variate Generation.
Communications of the ACM, 31, 2
(February, 1988) 216.
**********************************************************************
SUBROUTINE BTPEC(N,PP,ISEED,JX)
BINOMIAL RANDOM VARIATE GENERATOR
MEAN .LT. 30 -- INVERSE CDF
MEAN .GE. 30 -- ALGORITHM BTPE: ACCEPTANCE-REJECTION VIA
FOUR REGION COMPOSITION. THE FOUR REGIONS ARE A TRIANGLE
(SYMMETRIC IN THE CENTER), A PAIR OF PARALLELOGRAMS (ABOVE
THE TRIANGLE), AND EXPONENTIAL LEFT AND RIGHT TAILS.
BTPE REFERS TO BINOMIAL-TRIANGLE-PARALLELOGRAM-EXPONENTIAL.
BTPEC REFERS TO BTPE AND "COMBINED." THUS BTPE IS THE
RESEARCH AND BTPEC IS THE IMPLEMENTATION OF A COMPLETE
USABLE ALGORITHM.
REFERENCE: VORATAS KACHITVICHYANUKUL AND BRUCE SCHMEISER,
"BINOMIAL RANDOM VARIATE GENERATION,"
COMMUNICATIONS OF THE ACM, FORTHCOMING
WRITTEN: SEPTEMBER 1980.
LAST REVISED: MAY 1985, JULY 1987
REQUIRED SUBPROGRAM: RAND() -- A UNIFORM (0,1) RANDOM NUMBER
GENERATOR
ARGUMENTS
N : NUMBER OF BERNOULLI TRIALS (INPUT)
PP : PROBABILITY OF SUCCESS IN EACH TRIAL (INPUT)
ISEED: RANDOM NUMBER SEED (INPUT AND OUTPUT)
JX: RANDOMLY GENERATED OBSERVATION (OUTPUT)
VARIABLES
PSAVE: VALUE OF PP FROM THE LAST CALL TO BTPEC
NSAVE: VALUE OF N FROM THE LAST CALL TO BTPEC
XNP: VALUE OF THE MEAN FROM THE LAST CALL TO BTPEC
P: PROBABILITY USED IN THE GENERATION PHASE OF BTPEC
FFM: TEMPORARY VARIABLE EQUAL TO XNP + P
M: INTEGER VALUE OF THE CURRENT MODE
FM: DOUBLEING POINT VALUE OF THE CURRENT MODE
XNPQ: TEMPORARY VARIABLE USED IN SETUP AND SQUEEZING STEPS
P1: AREA OF THE TRIANGLE
C: HEIGHT OF THE PARALLELOGRAMS
XM: CENTER OF THE TRIANGLE
XL: LEFT END OF THE TRIANGLE
XR: RIGHT END OF THE TRIANGLE
AL: TEMPORARY VARIABLE
XLL: RATE FOR THE LEFT EXPONENTIAL TAIL
XLR: RATE FOR THE RIGHT EXPONENTIAL TAIL
P2: AREA OF THE PARALLELOGRAMS
P3: AREA OF THE LEFT EXPONENTIAL TAIL
P4: AREA OF THE RIGHT EXPONENTIAL TAIL
U: A U(0,P4) RANDOM VARIATE USED FIRST TO SELECT ONE OF THE
FOUR REGIONS AND THEN CONDITIONALLY TO GENERATE A VALUE
FROM THE REGION
V: A U(0,1) RANDOM NUMBER USED TO GENERATE THE RANDOM VALUE
(REGION 1) OR TRANSFORMED INTO THE VARIATE TO ACCEPT OR
REJECT THE CANDIDATE VALUE
IX: INTEGER CANDIDATE VALUE
X: PRELIMINARY CONTINUOUS CANDIDATE VALUE IN REGION 2 LOGIC
AND A DOUBLEING POINT IX IN THE ACCEPT/REJECT LOGIC
K: ABSOLUTE VALUE OF (IX-M)
F: THE HEIGHT OF THE SCALED DENSITY FUNCTION USED IN THE
ACCEPT/REJECT DECISION WHEN BOTH M AND IX ARE SMALL
ALSO USED IN THE INVERSE TRANSFORMATION