-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.f90
1613 lines (1242 loc) · 38.7 KB
/
random.f90
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
MODULE random
! A module for random number generation from the following distributions:
!
! Distribution Function/subroutine name
!
! Normal (Gaussian) random_normal
! Gamma random_gamma
! Chi-squared random_chisq
! Exponential random_exponential
! Weibull random_Weibull
! Beta random_beta
! t random_t
! Multivariate normal random_mvnorm
! Generalized inverse Gaussian random_inv_gauss
! Poisson random_Poisson
! Binomial random_binomial1 *
! random_binomial2 *
! Negative binomial random_neg_binomial
! von Mises random_von_Mises
! Cauchy random_Cauchy
!
! Generate a random ordering of the integers 1 .. N
! random_order
! Initialize (seed) the uniform random number generator for ANY compiler
! seed_random_number
! Lognormal - see note below.
! ** Two functions are provided for the binomial distribution.
! If the parameter values remain constant, it is recommended that the
! first function is used (random_binomial1). If one or both of the
! parameters change, use the second function (random_binomial2).
! The compilers own random number generator, SUBROUTINE RANDOM_NUMBER(r),
! is used to provide a source of uniformly distributed random numbers.
! N.B. At this stage, only one random number is generated at each call to
! one of the functions above.
! The module uses the following functions which are included here:
! bin_prob to calculate a single binomial probability
! lngamma to calculate the logarithm to base e of the gamma function
! Some of the code is adapted from Dagpunar's book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
!
! In most of Dagpunar's routines, there is a test to see whether the value
! of one or two floating-point parameters has changed since the last call.
! These tests have been replaced by using a logical variable FIRST.
! This should be set to .TRUE. on the first call using new values of the
! parameters, and .FALSE. if the parameter values are the same as for the
! previous call.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Lognormal distribution
! If X has a lognormal distribution, then log(X) is normally distributed.
! Here the logarithm is the natural logarithm, that is to base e, sometimes
! denoted as ln. To generate random variates from this distribution, generate
! a random deviate from the normal distribution with mean and variance equal
! to the mean and variance of the logarithms of X, then take its exponential.
! Relationship between the mean & variance of log(X) and the mean & variance
! of X, when X has a lognormal distribution.
! Let m = mean of log(X), and s^2 = variance of log(X)
! Then
! mean of X = exp(m + 0.5s^2)
! variance of X = (mean(X))^2.[exp(s^2) - 1]
! In the reverse direction (rarely used)
! variance of log(X) = log[1 + var(X)/(mean(X))^2]
! mean of log(X) = log(mean(X) - 0.5var(log(X))
! N.B. The above formulae relate to population parameters; they will only be
! approximate if applied to sample values.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
! Version 1.13, 2 October 2000
! Changes from version 1.01
! 1. The random_order, random_Poisson & random_binomial routines have been
! replaced with more efficient routines.
! 2. A routine, seed_random_number, has been added to seed the uniform random
! number generator. This requires input of the required number of seeds
! for the particular compiler from a specified I/O unit such as a keyboard.
! 3. Made compatible with Lahey's ELF90.
! 4. Marsaglia & Tsang algorithm used for random_gamma when shape parameter > 1.
! 5. INTENT for array f corrected in random_mvnorm.
! Author: Alan Miller
! CSIRO Division of Mathematical & Information Sciences
! Private Bag 10, Clayton South MDC
! Clayton 3169, Victoria, Australia
! Phone: (+61) 3 9545-8016 Fax: (+61) 3 9545-8080
! e-mail: amiller @ bigpond.net.au
IMPLICIT NONE
REAL, PRIVATE :: zero = 0.0, half = 0.5, one = 1.0, two = 2.0, &
vsmall = TINY(1.0), vlarge = HUGE(1.0)
PRIVATE :: integral
!INTEGER, PARAMETER :: dp = SELECTED_REAL_KIND(12, 60)
INTEGER, PARAMETER :: dp = 8
CONTAINS
FUNCTION random_normal() RESULT(fn_val)
! Adapted from the following Fortran 77 code
! ALGORITHM 712, COLLECTED ALGORITHMS FROM ACM.
! THIS WORK PUBLISHED IN TRANSACTIONS ON MATHEMATICAL SOFTWARE,
! VOL. 18, NO. 4, DECEMBER, 1992, PP. 434-435.
! The function random_normal() returns a normally distributed pseudo-random
! number with zero mean and unit variance.
! The algorithm uses the ratio of uniforms method of A.J. Kinderman
! and J.F. Monahan augmented with quadratic bounding curves.
REAL :: fn_val
! Local variables
REAL :: s = 0.449871, t = -0.386595, a = 0.19600, b = 0.25472, &
r1 = 0.27597, r2 = 0.27846, u, v, x, y, q
! Generate P = (u,v) uniform in rectangle enclosing acceptance region
DO
CALL RANDOM_NUMBER(u)
CALL RANDOM_NUMBER(v)
v = 1.7156 * (v - half)
! Evaluate the quadratic form
x = u - s
y = ABS(v) - t
q = x**2 + y*(a*y - b*x)
! Accept P if inside inner ellipse
IF (q < r1) EXIT
! Reject P if outside outer ellipse
IF (q > r2) CYCLE
! Reject P if outside acceptance region
IF (v**2 < -4.0*LOG(u)*u**2) EXIT
END DO
! Return ratio of P's coordinates as the normal deviate
fn_val = v/u
RETURN
END FUNCTION random_normal
FUNCTION random_gamma(s, first) RESULT(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! FUNCTION GENERATES A RANDOM GAMMA VARIATE.
! CALLS EITHER random_gamma1 (S > 1.0)
! OR random_exponential (S = 1.0)
! OR random_gamma2 (S < 1.0).
! S = SHAPE PARAMETER OF DISTRIBUTION (0 < REAL).
REAL, INTENT(IN) :: s
LOGICAL, INTENT(IN) :: first
REAL :: fn_val
IF (s <= zero) THEN
WRITE(*, *) 'SHAPE PARAMETER VALUE MUST BE POSITIVE'
STOP
END IF
IF (s > one) THEN
fn_val = random_gamma1(s, first)
ELSE IF (s < one) THEN
fn_val = random_gamma2(s, first)
ELSE
fn_val = random_exponential()
END IF
RETURN
END FUNCTION random_gamma
FUNCTION random_gamma1(s, first) RESULT(fn_val)
! Uses the algorithm in
! Marsaglia, G. and Tsang, W.W. (2000) `A simple method for generating
! gamma variables', Trans. om Math. Software (TOMS), vol.26(3), pp.363-372.
! Generates a random gamma deviate for shape parameter s >= 1.
REAL, INTENT(IN) :: s
LOGICAL, INTENT(IN) :: first
REAL :: fn_val
! Local variables
REAL, SAVE :: c, d
REAL :: u, v, x
IF (first) THEN
d = s - one/3.
c = one/SQRT(9.0*d)
END IF
! Start of main loop
DO
! Generate v = (1+cx)^3 where x is random normal; repeat if v <= 0.
DO
x = random_normal()
v = (one + c*x)**3
IF (v > zero) EXIT
END DO
! Generate uniform variable U
CALL RANDOM_NUMBER(u)
IF (u < one - 0.0331*x**4) THEN
fn_val = d*v
EXIT
ELSE IF (LOG(u) < half*x**2 + d*(one - v + LOG(v))) THEN
fn_val = d*v
EXIT
END IF
END DO
RETURN
END FUNCTION random_gamma1
FUNCTION random_gamma2(s, first) RESULT(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! FUNCTION GENERATES A RANDOM VARIATE IN [0,INFINITY) FROM
! A GAMMA DISTRIBUTION WITH DENSITY PROPORTIONAL TO
! GAMMA2**(S-1) * EXP(-GAMMA2),
! USING A SWITCHING METHOD.
! S = SHAPE PARAMETER OF DISTRIBUTION
! (REAL < 1.0)
REAL, INTENT(IN) :: s
LOGICAL, INTENT(IN) :: first
REAL :: fn_val
! Local variables
REAL :: r, x, w
REAL, SAVE :: a, p, c, uf, vr, d
IF (s <= zero .OR. s >= one) THEN
WRITE(*, *) 'SHAPE PARAMETER VALUE OUTSIDE PERMITTED RANGE'
STOP
END IF
IF (first) THEN ! Initialization, if necessary
a = one - s
p = a/(a + s*EXP(-a))
IF (s < vsmall) THEN
WRITE(*, *) 'SHAPE PARAMETER VALUE TOO SMALL'
STOP
END IF
c = one/s
uf = p*(vsmall/a)**s
vr = one - vsmall
d = a*LOG(a)
END IF
DO
CALL RANDOM_NUMBER(r)
IF (r >= vr) THEN
CYCLE
ELSE IF (r > p) THEN
x = a - LOG((one - r)/(one - p))
w = a*LOG(x)-d
ELSE IF (r > uf) THEN
x = a*(r/p)**c
w = x
ELSE
fn_val = zero
RETURN
END IF
CALL RANDOM_NUMBER(r)
IF (one-r <= w .AND. r > zero) THEN
IF (r*(w + one) >= one) CYCLE
IF (-LOG(r) <= w) CYCLE
END IF
EXIT
END DO
fn_val = x
RETURN
END FUNCTION random_gamma2
FUNCTION random_chisq(ndf, first) RESULT(fn_val)
! Generates a random variate from the chi-squared distribution with
! ndf degrees of freedom
INTEGER, INTENT(IN) :: ndf
LOGICAL, INTENT(IN) :: first
REAL :: fn_val
fn_val = two * random_gamma(half*ndf, first)
RETURN
END FUNCTION random_chisq
FUNCTION random_exponential() RESULT(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! FUNCTION GENERATES A RANDOM VARIATE IN [0,INFINITY) FROM
! A NEGATIVE EXPONENTIAL DlSTRIBUTION WlTH DENSITY PROPORTIONAL
! TO EXP(-random_exponential), USING INVERSION.
REAL :: fn_val
! Local variable
REAL :: r
DO
CALL RANDOM_NUMBER(r)
IF (r > zero) EXIT
END DO
fn_val = -LOG(r)
RETURN
END FUNCTION random_exponential
FUNCTION random_Weibull(a) RESULT(fn_val)
! Generates a random variate from the Weibull distribution with
! probability density:
! a
! a-1 -x
! f(x) = a.x e
REAL, INTENT(IN) :: a
REAL :: fn_val
! For speed, there is no checking that a is not zero or very small.
fn_val = random_exponential() ** (one/a)
RETURN
END FUNCTION random_Weibull
FUNCTION random_beta(aa, bb, first) RESULT(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! FUNCTION GENERATES A RANDOM VARIATE IN [0,1]
! FROM A BETA DISTRIBUTION WITH DENSITY
! PROPORTIONAL TO BETA**(AA-1) * (1-BETA)**(BB-1).
! USING CHENG'S LOG LOGISTIC METHOD.
! AA = SHAPE PARAMETER FROM DISTRIBUTION (0 < REAL)
! BB = SHAPE PARAMETER FROM DISTRIBUTION (0 < REAL)
REAL, INTENT(IN) :: aa, bb
LOGICAL, INTENT(IN) :: first
REAL :: fn_val
! Local variables
REAL, PARAMETER :: aln4 = 1.3862944
REAL :: a, b, g, r, s, x, y, z
REAL, SAVE :: d, f, h, t, c
LOGICAL, SAVE :: swap
IF (aa <= zero .OR. bb <= zero) THEN
WRITE(*, *) 'IMPERMISSIBLE SHAPE PARAMETER VALUE(S)'
STOP
END IF
IF (first) THEN ! Initialization, if necessary
a = aa
b = bb
swap = b > a
IF (swap) THEN
g = b
b = a
a = g
END IF
d = a/b
f = a+b
IF (b > one) THEN
h = SQRT((two*a*b - f)/(f - two))
t = one
ELSE
h = b
t = one/(one + (a/(vlarge*b))**b)
END IF
c = a+h
END IF
DO
CALL RANDOM_NUMBER(r)
CALL RANDOM_NUMBER(x)
s = r*r*x
IF (r < vsmall .OR. s <= zero) CYCLE
IF (r < t) THEN
x = LOG(r/(one - r))/h
y = d*EXP(x)
z = c*x + f*LOG((one + d)/(one + y)) - aln4
IF (s - one > z) THEN
IF (s - s*z > one) CYCLE
IF (LOG(s) > z) CYCLE
END IF
fn_val = y/(one + y)
ELSE
IF (4.0*s > (one + one/d)**f) CYCLE
fn_val = one
END IF
EXIT
END DO
IF (swap) fn_val = one - fn_val
RETURN
END FUNCTION random_beta
FUNCTION random_t(m) RESULT(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! FUNCTION GENERATES A RANDOM VARIATE FROM A
! T DISTRIBUTION USING KINDERMAN AND MONAHAN'S RATIO METHOD.
! M = DEGREES OF FREEDOM OF DISTRIBUTION
! (1 <= 1NTEGER)
INTEGER, INTENT(IN) :: m
REAL :: fn_val
! Local variables
REAL, SAVE :: s, c, a, f, g
REAL :: r, x, v
REAL, PARAMETER :: three = 3.0, four = 4.0, quart = 0.25, &
five = 5.0, sixteen = 16.0
INTEGER :: mm = 0
IF (m < 1) THEN
WRITE(*, *) 'IMPERMISSIBLE DEGREES OF FREEDOM'
STOP
END IF
IF (m /= mm) THEN ! Initialization, if necessary
s = m
c = -quart*(s + one)
a = four/(one + one/s)**c
f = sixteen/a
IF (m > 1) THEN
g = s - one
g = ((s + one)/g)**c*SQRT((s+s)/g)
ELSE
g = one
END IF
mm = m
END IF
DO
CALL RANDOM_NUMBER(r)
IF (r <= zero) CYCLE
CALL RANDOM_NUMBER(v)
x = (two*v - one)*g/r
v = x*x
IF (v > five - a*r) THEN
IF (m >= 1 .AND. r*(v + three) > f) CYCLE
IF (r > (one + v/s)**c) CYCLE
END IF
EXIT
END DO
fn_val = x
RETURN
END FUNCTION random_t
SUBROUTINE random_mvnorm(n, h, d, f, first, x, ier)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! N.B. An extra argument, ier, has been added to Dagpunar's routine
! SUBROUTINE GENERATES AN N VARIATE RANDOM NORMAL
! VECTOR USING A CHOLESKY DECOMPOSITION.
! ARGUMENTS:
! N = NUMBER OF VARIATES IN VECTOR
! (INPUT,INTEGER >= 1)
! H(J) = J'TH ELEMENT OF VECTOR OF MEANS
! (INPUT,REAL)
! X(J) = J'TH ELEMENT OF DELIVERED VECTOR
! (OUTPUT,REAL)
!
! D(J*(J-1)/2+I) = (I,J)'TH ELEMENT OF VARIANCE MATRIX (J> = I)
! (INPUT,REAL)
! F((J-1)*(2*N-J)/2+I) = (I,J)'TH ELEMENT OF LOWER TRIANGULAR
! DECOMPOSITION OF VARIANCE MATRIX (J <= I)
! (OUTPUT,REAL)
! FIRST = .TRUE. IF THIS IS THE FIRST CALL OF THE ROUTINE
! OR IF THE DISTRIBUTION HAS CHANGED SINCE THE LAST CALL OF THE ROUTINE.
! OTHERWISE SET TO .FALSE.
! (INPUT,LOGICAL)
! ier = 1 if the input covariance matrix is not +ve definite
! = 0 otherwise
INTEGER, INTENT(IN) :: n
REAL, INTENT(IN) :: h(:), d(:) ! d(n*(n+1)/2)
REAL, INTENT(IN OUT) :: f(:) ! f(n*(n+1)/2)
REAL, INTENT(OUT) :: x(:)
LOGICAL, INTENT(IN) :: first
INTEGER, INTENT(OUT) :: ier
! Local variables
INTEGER :: j, i, m
REAL :: y, v
INTEGER, SAVE :: n2
IF (n < 1) THEN
WRITE(*, *) 'SIZE OF VECTOR IS NON POSITIVE'
STOP
END IF
ier = 0
IF (first) THEN ! Initialization, if necessary
n2 = 2*n
IF (d(1) < zero) THEN
ier = 1
RETURN
END IF
f(1) = SQRT(d(1))
y = one/f(1)
DO j = 2,n
f(j) = d(1+j*(j-1)/2) * y
END DO
DO i = 2,n
v = d(i*(i-1)/2+i)
DO m = 1,i-1
v = v - f((m-1)*(n2-m)/2+i)**2
END DO
IF (v < zero) THEN
ier = 1
RETURN
END IF
v = SQRT(v)
y = one/v
f((i-1)*(n2-i)/2+i) = v
DO j = i+1,n
v = d(j*(j-1)/2+i)
DO m = 1,i-1
v = v - f((m-1)*(n2-m)/2+i)*f((m-1)*(n2-m)/2 + j)
END DO ! m = 1,i-1
f((i-1)*(n2-i)/2 + j) = v*y
END DO ! j = i+1,n
END DO ! i = 2,n
END IF
x(1:n) = h(1:n)
DO j = 1,n
y = random_normal()
DO i = j,n
x(i) = x(i) + f((j-1)*(n2-j)/2 + i) * y
END DO ! i = j,n
END DO ! j = 1,n
RETURN
END SUBROUTINE random_mvnorm
FUNCTION random_inv_gauss(h, b, first) RESULT(fn_val)
! Adapted from Fortran 77 code from the book:
! Dagpunar, J. 'Principles of random variate generation'
! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
! FUNCTION GENERATES A RANDOM VARIATE IN [0,INFINITY] FROM
! A REPARAMETERISED GENERALISED INVERSE GAUSSIAN (GIG) DISTRIBUTION
! WITH DENSITY PROPORTIONAL TO GIG**(H-1) * EXP(-0.5*B*(GIG+1/GIG))
! USING A RATIO METHOD.
! H = PARAMETER OF DISTRIBUTION (0 <= REAL)
! B = PARAMETER OF DISTRIBUTION (0 < REAL)
REAL, INTENT(IN) :: h, b
LOGICAL, INTENT(IN) :: first
REAL :: fn_val
! Local variables
REAL :: ym, xm, r, w, r1, r2, x
REAL, SAVE :: a, c, d, e
REAL, PARAMETER :: quart = 0.25
IF (h < zero .OR. b <= zero) THEN
WRITE(*, *) 'IMPERMISSIBLE DISTRIBUTION PARAMETER VALUES'
STOP
END IF
IF (first) THEN ! Initialization, if necessary
IF (h > quart*b*SQRT(vlarge)) THEN
WRITE(*, *) 'THE RATIO H:B IS TOO SMALL'
STOP
END IF
e = b*b
d = h + one
ym = (-d + SQRT(d*d + e))/b
IF (ym < vsmall) THEN
WRITE(*, *) 'THE VALUE OF B IS TOO SMALL'
STOP
END IF
d = h - one
xm = (d + SQRT(d*d + e))/b
d = half*d
e = -quart*b
r = xm + one/xm
w = xm*ym
a = w**(-half*h) * SQRT(xm/ym) * EXP(-e*(r - ym - one/ym))
IF (a < vsmall) THEN
WRITE(*, *) 'THE VALUE OF H IS TOO LARGE'
STOP
END IF
c = -d*LOG(xm) - e*r
END IF
DO
CALL RANDOM_NUMBER(r1)
IF (r1 <= zero) CYCLE
CALL RANDOM_NUMBER(r2)
x = a*r2/r1
IF (x <= zero) CYCLE
IF (LOG(r1) < d*LOG(x) + e*(x + one/x) + c) EXIT
END DO
fn_val = x
RETURN
END FUNCTION random_inv_gauss
FUNCTION random_Poisson(mu, first) RESULT(ival)
!**********************************************************************
! Translated to Fortran 90 by Alan Miller from:
! RANLIB
!
! Library of Fortran Routines for Random Number Generation
!
! Compiled and Written by:
!
! Barry W. Brown
! James Lovato
!
! Department of Biomathematics, Box 237
! The University of Texas, M.D. Anderson Cancer Center
! 1515 Holcombe Boulevard
! Houston, TX 77030
!
! This work was supported by grant CA-16672 from the National Cancer Institute.
! GENerate POIsson random deviate
! Function
! Generates a single random deviate from a Poisson distribution with mean mu.
! Arguments
! mu --> The mean of the Poisson distribution from which
! a random deviate is to be generated.
! REAL mu
! Method
! For details see:
! Ahrens, J.H. and Dieter, U.
! Computer Generation of Poisson Deviates
! From Modified Normal Distributions.
! ACM Trans. Math. Software, 8, 2
! (June 1982),163-179
! TABLES: COEFFICIENTS A0-A7 FOR STEP F. FACTORIALS FACT
! COEFFICIENTS A(K) - FOR PX = FK*V*V*SUM(A(K)*V**K)-DEL
! SEPARATION OF CASES A AND B
! .. Scalar Arguments ..
REAL, INTENT(IN) :: mu
LOGICAL, INTENT(IN) :: first
INTEGER :: ival
! ..
! .. Local Scalars ..
REAL :: b1, b2, c, c0, c1, c2, c3, del, difmuk, e, fk, fx, fy, g, &
omega, px, py, t, u, v, x, xx
REAL, SAVE :: s, d, p, q, p0
INTEGER :: j, k, kflag
LOGICAL, SAVE :: full_init
INTEGER, SAVE :: l, m
! ..
! .. Local Arrays ..
REAL, SAVE :: pp(35)
! ..
! .. Data statements ..
REAL, PARAMETER :: a0 = -.5, a1 = .3333333, a2 = -.2500068, a3 = .2000118, &
a4 = -.1661269, a5 = .1421878, a6 = -.1384794, &
a7 = .1250060
REAL, PARAMETER :: fact(10) = (/ 1., 1., 2., 6., 24., 120., 720., 5040., &
40320., 362880. /)
! ..
! .. Executable Statements ..
IF (mu > 10.0) THEN
! C A S E A. (RECALCULATION OF S, D, L IF MU HAS CHANGED)
IF (first) THEN
s = SQRT(mu)
d = 6.0*mu*mu
! THE POISSON PROBABILITIES PK EXCEED THE DISCRETE NORMAL
! PROBABILITIES FK WHENEVER K >= M(MU). L=IFIX(MU-1.1484)
! IS AN UPPER BOUND TO M(MU) FOR ALL MU >= 10 .
l = mu - 1.1484
full_init = .false.
END IF
! STEP N. NORMAL SAMPLE - random_normal() FOR STANDARD NORMAL DEVIATE
g = mu + s*random_normal()
IF (g > 0.0) THEN
ival = g
! STEP I. IMMEDIATE ACCEPTANCE IF ival IS LARGE ENOUGH
IF (ival>=l) RETURN
! STEP S. SQUEEZE ACCEPTANCE - SAMPLE U
fk = ival
difmuk = mu - fk
CALL RANDOM_NUMBER(u)
IF (d*u >= difmuk*difmuk*difmuk) RETURN
END IF
! STEP P. PREPARATIONS FOR STEPS Q AND H.
! (RECALCULATIONS OF PARAMETERS IF NECESSARY)
! .3989423=(2*PI)**(-.5) .416667E-1=1./24. .1428571=1./7.
! THE QUANTITIES B1, B2, C3, C2, C1, C0 ARE FOR THE HERMITE
! APPROXIMATIONS TO THE DISCRETE NORMAL PROBABILITIES FK.
! C=.1069/MU GUARANTEES MAJORIZATION BY THE 'HAT'-FUNCTION.
IF (.NOT. full_init) THEN
omega = .3989423/s
b1 = .4166667E-1/mu
b2 = .3*b1*b1
c3 = .1428571*b1*b2
c2 = b2 - 15.*c3
c1 = b1 - 6.*b2 + 45.*c3
c0 = 1. - b1 + 3.*b2 - 15.*c3
c = .1069/mu
full_init = .true.
END IF
IF (g < 0.0) GO TO 50
! 'SUBROUTINE' F IS CALLED (KFLAG=0 FOR CORRECT RETURN)
kflag = 0
GO TO 70
! STEP Q. QUOTIENT ACCEPTANCE (RARE CASE)
40 IF (fy-u*fy <= py*EXP(px-fx)) RETURN
! STEP E. EXPONENTIAL SAMPLE - random_exponential() FOR STANDARD EXPONENTIAL
! DEVIATE E AND SAMPLE T FROM THE LAPLACE 'HAT'
! (IF T <= -.6744 THEN PK < FK FOR ALL MU >= 10.)
50 e = random_exponential()
CALL RANDOM_NUMBER(u)
u = u + u - one
t = 1.8 + SIGN(e, u)
IF (t <= (-.6744)) GO TO 50
ival = mu + s*t
fk = ival
difmuk = mu - fk
! 'SUBROUTINE' F IS CALLED (KFLAG=1 FOR CORRECT RETURN)
kflag = 1
GO TO 70
! STEP H. HAT ACCEPTANCE (E IS REPEATED ON REJECTION)
60 IF (c*ABS(u) > py*EXP(px+e) - fy*EXP(fx+e)) GO TO 50
RETURN
! STEP F. 'SUBROUTINE' F. CALCULATION OF PX, PY, FX, FY.
! CASE ival < 10 USES FACTORIALS FROM TABLE FACT
70 IF (ival>=10) GO TO 80
px = -mu
py = mu**ival/fact(ival+1)
GO TO 110
! CASE ival >= 10 USES POLYNOMIAL APPROXIMATION
! A0-A7 FOR ACCURACY WHEN ADVISABLE
! .8333333E-1=1./12. .3989423=(2*PI)**(-.5)
80 del = .8333333E-1/fk
del = del - 4.8*del*del*del
v = difmuk/fk
IF (ABS(v)>0.25) THEN
px = fk*LOG(one + v) - difmuk - del
ELSE
px = fk*v*v* (((((((a7*v+a6)*v+a5)*v+a4)*v+a3)*v+a2)*v+a1)*v+a0) - del
END IF
py = .3989423/SQRT(fk)
110 x = (half - difmuk)/s
xx = x*x
fx = -half*xx
fy = omega* (((c3*xx + c2)*xx + c1)*xx + c0)
IF (kflag <= 0) GO TO 40
GO TO 60
!---------------------------------------------------------------------------
! C A S E B. mu < 10
! START NEW TABLE AND CALCULATE P0 IF NECESSARY
ELSE
IF (first) THEN
m = MAX(1, INT(mu))
l = 0
p = EXP(-mu)
q = p
p0 = p
END IF
! STEP U. UNIFORM SAMPLE FOR INVERSION METHOD
DO
CALL RANDOM_NUMBER(u)
ival = 0
IF (u <= p0) RETURN
! STEP T. TABLE COMPARISON UNTIL THE END PP(L) OF THE
! PP-TABLE OF CUMULATIVE POISSON PROBABILITIES
! (0.458=PP(9) FOR MU=10)
IF (l == 0) GO TO 150
j = 1
IF (u > 0.458) j = MIN(l, m)
DO k = j, l
IF (u <= pp(k)) GO TO 180
END DO
IF (l == 35) CYCLE
! STEP C. CREATION OF NEW POISSON PROBABILITIES P
! AND THEIR CUMULATIVES Q=PP(K)
150 l = l + 1
DO k = l, 35
p = p*mu / k
q = q + p
pp(k) = q
IF (u <= q) GO TO 170
END DO
l = 35
END DO
170 l = k
180 ival = k
RETURN
END IF
RETURN
END FUNCTION random_Poisson
FUNCTION random_binomial1(n, p, first) RESULT(ival)
! FUNCTION GENERATES A RANDOM BINOMIAL VARIATE USING C.D.Kemp's method.
! This algorithm is suitable when many random variates are required
! with the SAME parameter values for n & p.
! P = BERNOULLI SUCCESS PROBABILITY
! (0 <= REAL <= 1)
! N = NUMBER OF BERNOULLI TRIALS
! (1 <= INTEGER)
! FIRST = .TRUE. for the first call using the current parameter values
! = .FALSE. if the values of (n,p) are unchanged from last call
! Reference: Kemp, C.D. (1986). `A modal method for generating binomial
! variables', Commun. Statist. - Theor. Meth. 15(3), 805-813.
INTEGER, INTENT(IN) :: n
REAL, INTENT(IN) :: p
LOGICAL, INTENT(IN) :: first
INTEGER :: ival
! Local variables
INTEGER :: ru, rd
INTEGER, SAVE :: r0
REAL :: u, pd, pu
REAL, SAVE :: odds_ratio, p_r
REAL, PARAMETER :: zero = 0.0, one = 1.0
IF (first) THEN
r0 = (n+1)*p
p_r = bin_prob(n, p, r0)
odds_ratio = p / (one - p)
END IF
CALL RANDOM_NUMBER(u)
u = u - p_r
IF (u < zero) THEN
ival = r0
RETURN
END IF
pu = p_r
ru = r0
pd = p_r
rd = r0
DO
rd = rd - 1
IF (rd >= 0) THEN
pd = pd * (rd+1) / (odds_ratio * (n-rd))
u = u - pd
IF (u < zero) THEN
ival = rd
RETURN
END IF
END IF
ru = ru + 1
IF (ru <= n) THEN
pu = pu * (n-ru+1) * odds_ratio / ru
u = u - pu
IF (u < zero) THEN
ival = ru
RETURN
END IF
END IF
END DO
! This point should not be reached, but just in case:
ival = r0
RETURN
END FUNCTION random_binomial1
FUNCTION bin_prob(n, p, r) RESULT(fn_val)