EMPIRE DA  v1.9.1
Data assimilation codes using EMPIRE communication
 All Classes Files Functions Variables Pages
random_d.f90
Go to the documentation of this file.
1 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
2 !!! Time-stamp: <2014-09-22 15:52:53 pbrowne>
22 MODULE random
23 ! Generate a random ordering of the integers 1 .. N
24 ! random_order
25 ! Initialize (seed) the uniform random number generator for ANY compiler
26 ! seed_random_number
27 
28 ! Lognormal - see note below.
29 
30 ! ** Two functions are provided for the binomial distribution.
31 ! If the parameter values remain constant, it is recommended that the
32 ! first function is used (random_binomial1). If one or both of the
33 ! parameters change, use the second function (random_binomial2).
34 
35 ! The compilers own random number generator, SUBROUTINE RANDOM_NUMBER(r),
36 ! is used to provide a source of uniformly distributed random numbers.
37 
38 ! N.B. At this stage, only one random number is generated at each call to
39 ! one of the functions above.
40 
41 ! The module uses the following functions which are included here:
42 ! bin_prob to calculate a single binomial probability
43 ! lngamma to calculate the logarithm to base e of the gamma function
44 
45 ! Some of the code is adapted from Dagpunar's book:
46 ! Dagpunar, J. 'Principles of random variate generation'
47 ! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
48 !
49 ! In most of Dagpunar's routines, there is a test to see whether the value
50 ! of one or two floating-point parameters has changed since the last call.
51 ! These tests have been replaced by using a logical variable FIRST.
52 ! This should be set to .TRUE. on the first call using new values of the
53 ! parameters, and .FALSE. if the parameter values are the same as for the
54 ! previous call.
55 
56 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
57 ! Lognormal distribution
58 ! If X has a lognormal distribution, then log(X) is normally distributed.
59 ! Here the logarithm is the natural logarithm, that is to base e, sometimes
60 ! denoted as ln. To generate random variates from this distribution, generate
61 ! a random deviate from the normal distribution with mean and variance equal
62 ! to the mean and variance of the logarithms of X, then take its exponential.
63 
64 ! Relationship between the mean & variance of log(X) and the mean & variance
65 ! of X, when X has a lognormal distribution.
66 ! Let m = mean of log(X), and s^2 = variance of log(X)
67 ! Then
68 ! mean of X = exp(m + 0.5s^2)
69 ! variance of X = (mean(X))^2.[exp(s^2) - 1]
70 
71 ! In the reverse direction (rarely used)
72 ! variance of log(X) = log[1 + var(X)/(mean(X))^2]
73 ! mean of log(X) = log(mean(X) - 0.5var(log(X))
74 
75 ! N.B. The above formulae relate to population parameters; they will only be
76 ! approximate if applied to sample values.
77 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
78 
79 ! Version 1.13, 2 October 2000
80 ! Changes from version 1.01
81 ! 1. The random_order, random_Poisson & random_binomial routines have been
82 ! replaced with more efficient routines.
83 ! 2. A routine, seed_random_number, has been added to seed the uniform random
84 ! number generator. This requires input of the required number of seeds
85 ! for the particular compiler from a specified I/O unit such as a keyboard.
86 ! 3. Made compatible with Lahey's ELF90.
87 ! 4. Marsaglia & Tsang algorithm used for random_gamma when shape parameter > 1.
88 ! 5. INTENT for array f corrected in random_mvnorm.
89 
90 ! Author: Alan Miller
91 ! CSIRO Division of Mathematical & Information Sciences
92 ! Private Bag 10, Clayton South MDC
93 ! Clayton 3169, Victoria, Australia
94 ! Phone: (+61) 3 9545-8016 Fax: (+61) 3 9545-8080
95 ! e-mail: amiller @ bigpond.net.au
96 
97 IMPLICIT NONE
98 real(kind=kind(1.0D+0)), PRIVATE :: zero = 0.0, half = 0.5, one = 1.0, two = 2.0, &
99  vsmall = tiny(1.0), vlarge = huge(1.0)
100 PRIVATE :: integral
101 INTEGER, PARAMETER :: dp = selected_real_kind(12, 60)
102 
103 
104 CONTAINS
105 
108 FUNCTION random_normal() RESULT(fn_val)
109 
110 ! Adapted from the following Fortran 77 code
111 ! ALGORITHM 712, COLLECTED ALGORITHMS FROM ACM.
112 ! THIS WORK PUBLISHED IN TRANSACTIONS ON MATHEMATICAL SOFTWARE,
113 ! VOL. 18, NO. 4, DECEMBER, 1992, PP. 434-435.
114 
115 ! The function random_normal() returns a normally distributed pseudo-random
116 ! number with zero mean and unit variance.
117 
118 ! The algorithm uses the ratio of uniforms method of A.J. Kinderman
119 ! and J.F. Monahan augmented with quadratic bounding curves.
120 
121 real(kind=kind(1.0D+0)) :: fn_val
122 
123 ! Local variables
124 real(kind=kind(1.0D+0)) :: s = 0.449871, t = -0.386595, a = 0.19600, b = 0.25472, &
125  r1 = 0.27597, r2 = 0.27846, u, v, x, y, q
126 
127 ! Generate P = (u,v) uniform in rectangle enclosing acceptance region
128 
129 DO
130  CALL random_number(u)
131  CALL random_number(v)
132  v = 1.7156 * (v - half)
133 
134 ! Evaluate the quadratic form
135  x = u - s
136  y = abs(v) - t
137  q = x**2 + y*(a*y - b*x)
138 
139 ! Accept P if inside inner ellipse
140  IF (q < r1) EXIT
141 ! Reject P if outside outer ellipse
142  IF (q > r2) cycle
143 ! Reject P if outside acceptance region
144  IF (v**2 < -4.0*log(u)*u**2) EXIT
145 END DO
146 
147 ! Return ratio of P's coordinates as the normal deviate
148 fn_val = v/u
149 RETURN
150 
151 END FUNCTION random_normal
152 
153 
154 FUNCTION random_gamma(s, first) RESULT(fn_val)
155 
156 ! Adapted from Fortran 77 code from the book:
157 ! Dagpunar, J. 'Principles of random variate generation'
158 ! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
159 
160 ! FUNCTION GENERATES A RANDOM GAMMA VARIATE.
161 ! CALLS EITHER random_gamma1 (S > 1.0)
162 ! OR random_exponential (S = 1.0)
163 ! OR random_gamma2 (S < 1.0).
164 
165 ! S = SHAPE PARAMETER OF DISTRIBUTION (0 < REAL).
166 
167 real(kind=kind(1.0D+0)), INTENT(IN) :: s
168 LOGICAL, INTENT(IN) :: first
169 real(kind=kind(1.0D+0)) :: fn_val
170 
171 IF (s <= zero) THEN
172  WRITE(*, *) 'SHAPE PARAMETER VALUE MUST BE POSITIVE'
173  stop
174 END IF
175 
176 IF (s > one) THEN
177  fn_val = random_gamma1(s, first)
178 ELSE IF (s < one) THEN
179  fn_val = random_gamma2(s, first)
180 ELSE
181  fn_val = random_exponential()
182 END IF
183 
184 RETURN
185 END FUNCTION random_gamma
186 
187 
188 
189 FUNCTION random_gamma1(s, first) RESULT(fn_val)
190 
191 ! Uses the algorithm in
192 ! Marsaglia, G. and Tsang, W.W. (2000) `A simple method for generating
193 ! gamma variables', Trans. om Math. Software (TOMS), vol.26(3), pp.363-372.
194 
195 ! Generates a random gamma deviate for shape parameter s >= 1.
196 
197 real(kind=kind(1.0D+0)), INTENT(IN) :: s
198 LOGICAL, INTENT(IN) :: first
199 real(kind=kind(1.0D+0)) :: fn_val
200 
201 ! Local variables
202 real(kind=kind(1.0D+0)), SAVE :: c, d
203 real(kind=kind(1.0D+0)) :: u, v, x
204 
205 IF (first) THEN
206  d = s - one/3.
207  c = one/sqrt(9.0*d)
208 END IF
209 
210 ! Start of main loop
211 DO
212 
213 ! Generate v = (1+cx)^3 where x is random normal; repeat if v <= 0.
214 
215  DO
216  x = random_normal()
217  v = (one + c*x)**3
218  IF (v > zero) EXIT
219  END DO
220 
221 ! Generate uniform variable U
222 
223  CALL random_number(u)
224  IF (u < one - 0.0331*x**4) THEN
225  fn_val = d*v
226  EXIT
227  ELSE IF (log(u) < half*x**2 + d*(one - v + log(v))) THEN
228  fn_val = d*v
229  EXIT
230  END IF
231 END DO
232 
233 RETURN
234 END FUNCTION random_gamma1
235 
236 
237 
238 FUNCTION random_gamma2(s, first) RESULT(fn_val)
239 
240 ! Adapted from Fortran 77 code from the book:
241 ! Dagpunar, J. 'Principles of random variate generation'
242 ! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
243 
244 ! FUNCTION GENERATES A RANDOM VARIATE IN [0,INFINITY) FROM
245 ! A GAMMA DISTRIBUTION WITH DENSITY PROPORTIONAL TO
246 ! GAMMA2**(S-1) * EXP(-GAMMA2),
247 ! USING A SWITCHING METHOD.
248 
249 ! S = SHAPE PARAMETER OF DISTRIBUTION
250 ! (REAL < 1.0)
251 
252 real(kind=kind(1.0D+0)), INTENT(IN) :: s
253 LOGICAL, INTENT(IN) :: first
254 real(kind=kind(1.0D+0)) :: fn_val
255 
256 ! Local variables
257 real(kind=kind(1.0D+0)) :: r, x, w
258 real(kind=kind(1.0D+0)), SAVE :: a, p, c, uf, vr, d
259 
260 IF (s <= zero .OR. s >= one) THEN
261  WRITE(*, *) 'SHAPE PARAMETER VALUE OUTSIDE PERMITTED RANGE'
262  stop
263 END IF
264 
265 IF (first) THEN ! Initialization, if necessary
266  a = one - s
267  p = a/(a + s*exp(-a))
268  IF (s < vsmall) THEN
269  WRITE(*, *) 'SHAPE PARAMETER VALUE TOO SMALL'
270  stop
271  END IF
272  c = one/s
273  uf = p*(vsmall/a)**s
274  vr = one - vsmall
275  d = a*log(a)
276 END IF
277 
278 DO
279  CALL random_number(r)
280  IF (r >= vr) THEN
281  cycle
282  ELSE IF (r > p) THEN
283  x = a - log((one - r)/(one - p))
284  w = a*log(x)-d
285  ELSE IF (r > uf) THEN
286  x = a*(r/p)**c
287  w = x
288  ELSE
289  fn_val = zero
290  RETURN
291  END IF
292 
293  CALL random_number(r)
294  IF (one-r <= w .AND. r > zero) THEN
295  IF (r*(w + one) >= one) cycle
296  IF (-log(r) <= w) cycle
297  END IF
298  EXIT
299 END DO
300 
301 fn_val = x
302 RETURN
303 
304 END FUNCTION random_gamma2
305 
306 
307 
308 FUNCTION random_chisq(ndf, first) RESULT(fn_val)
309 
310 ! Generates a random variate from the chi-squared distribution with
311 ! ndf degrees of freedom
312 
313 INTEGER, INTENT(IN) :: ndf
314 LOGICAL, INTENT(IN) :: first
315 real(kind=kind(1.0D+0)) :: fn_val
316 
317 fn_val = two * random_gamma(half*ndf, first)
318 RETURN
319 
320 END FUNCTION random_chisq
321 
322 
323 
324 FUNCTION random_exponential() RESULT(fn_val)
325 
326 ! Adapted from Fortran 77 code from the book:
327 ! Dagpunar, J. 'Principles of random variate generation'
328 ! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
329 
330 ! FUNCTION GENERATES A RANDOM VARIATE IN [0,INFINITY) FROM
331 ! A NEGATIVE EXPONENTIAL DlSTRIBUTION WlTH DENSITY PROPORTIONAL
332 ! TO EXP(-random_exponential), USING INVERSION.
333 
334 real(kind=kind(1.0D+0)) :: fn_val
335 
336 ! Local variable
337 real(kind=kind(1.0D+0)) :: r
338 
339 DO
340  CALL random_number(r)
341  IF (r > zero) EXIT
342 END DO
343 
344 fn_val = -log(r)
345 RETURN
346 
347 END FUNCTION random_exponential
348 
349 
350 
351 FUNCTION random_weibull(a) RESULT(fn_val)
352 
353 ! Generates a random variate from the Weibull distribution with
354 ! probability density:
355 ! a
356 ! a-1 -x
357 ! f(x) = a.x e
358 
359 real(kind=kind(1.0D+0)), INTENT(IN) :: a
360 real(kind=kind(1.0D+0)) :: fn_val
361 
362 ! For speed, there is no checking that a is not zero or very small.
363 
364 fn_val = random_exponential() ** (one/a)
365 RETURN
366 
367 END FUNCTION random_weibull
368 
369 
370 
371 FUNCTION random_beta(aa, bb, first) RESULT(fn_val)
372 
373 ! Adapted from Fortran 77 code from the book:
374 ! Dagpunar, J. 'Principles of random variate generation'
375 ! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
376 
377 ! FUNCTION GENERATES A RANDOM VARIATE IN [0,1]
378 ! FROM A BETA DISTRIBUTION WITH DENSITY
379 ! PROPORTIONAL TO BETA**(AA-1) * (1-BETA)**(BB-1).
380 ! USING CHENG'S LOG LOGISTIC METHOD.
381 
382 ! AA = SHAPE PARAMETER FROM DISTRIBUTION (0 < REAL)
383 ! BB = SHAPE PARAMETER FROM DISTRIBUTION (0 < REAL)
384 
385 real(kind=kind(1.0D+0)), INTENT(IN) :: aa, bb
386 LOGICAL, INTENT(IN) :: first
387 real(kind=kind(1.0D+0)) :: fn_val
388 
389 ! Local variables
390 real(kind=kind(1.0D+0)), PARAMETER :: aln4 = 1.3862944
391 real(kind=kind(1.0D+0)) :: a, b, g, r, s, x, y, z
392 real(kind=kind(1.0D+0)), SAVE :: d, f, h, t, c
393 LOGICAL, SAVE :: swap
394 
395 IF (aa <= zero .OR. bb <= zero) THEN
396  WRITE(*, *) 'IMPERMISSIBLE SHAPE PARAMETER VALUE(S)'
397  stop
398 END IF
399 
400 IF (first) THEN ! Initialization, if necessary
401  a = aa
402  b = bb
403  swap = b > a
404  IF (swap) THEN
405  g = b
406  b = a
407  a = g
408  END IF
409  d = a/b
410  f = a+b
411  IF (b > one) THEN
412  h = sqrt((two*a*b - f)/(f - two))
413  t = one
414  ELSE
415  h = b
416  t = one/(one + (a/(vlarge*b))**b)
417  END IF
418  c = a+h
419 END IF
420 
421 DO
422  CALL random_number(r)
423  CALL random_number(x)
424  s = r*r*x
425  IF (r < vsmall .OR. s <= zero) cycle
426  IF (r < t) THEN
427  x = log(r/(one - r))/h
428  y = d*exp(x)
429  z = c*x + f*log((one + d)/(one + y)) - aln4
430  IF (s - one > z) THEN
431  IF (s - s*z > one) cycle
432  IF (log(s) > z) cycle
433  END IF
434  fn_val = y/(one + y)
435  ELSE
436  IF (4.0*s > (one + one/d)**f) cycle
437  fn_val = one
438  END IF
439  EXIT
440 END DO
441 
442 IF (swap) fn_val = one - fn_val
443 RETURN
444 END FUNCTION random_beta
445 
446 
447 
448 FUNCTION random_t(m) RESULT(fn_val)
449 
450 ! Adapted from Fortran 77 code from the book:
451 ! Dagpunar, J. 'Principles of random variate generation'
452 ! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
453 
454 ! FUNCTION GENERATES A RANDOM VARIATE FROM A
455 ! T DISTRIBUTION USING KINDERMAN AND MONAHAN'S RATIO METHOD.
456 
457 ! M = DEGREES OF FREEDOM OF DISTRIBUTION
458 ! (1 <= 1NTEGER)
459 
460 INTEGER, INTENT(IN) :: m
461 real(kind=kind(1.0D+0)) :: fn_val
462 
463 ! Local variables
464 real(kind=kind(1.0D+0)), SAVE :: s, c, a, f, g
465 real(kind=kind(1.0D+0)) :: r, x, v
466 
467 real(kind=kind(1.0D+0)), PARAMETER :: three = 3.0, four = 4.0, quart = 0.25, &
468  five = 5.0, sixteen = 16.0
469 INTEGER :: mm = 0
470 
471 IF (m < 1) THEN
472  WRITE(*, *) 'IMPERMISSIBLE DEGREES OF FREEDOM'
473  stop
474 END IF
475 
476 IF (m /= mm) THEN ! Initialization, if necessary
477  s = m
478  c = -quart*(s + one)
479  a = four/(one + one/s)**c
480  f = sixteen/a
481  IF (m > 1) THEN
482  g = s - one
483  g = ((s + one)/g)**c*sqrt((s+s)/g)
484  ELSE
485  g = one
486  END IF
487  mm = m
488 END IF
489 
490 DO
491  CALL random_number(r)
492  IF (r <= zero) cycle
493  CALL random_number(v)
494  x = (two*v - one)*g/r
495  v = x*x
496  IF (v > five - a*r) THEN
497  IF (m >= 1 .AND. r*(v + three) > f) cycle
498  IF (r > (one + v/s)**c) cycle
499  END IF
500  EXIT
501 END DO
502 
503 fn_val = x
504 RETURN
505 END FUNCTION random_t
506 
507 
508 
509 SUBROUTINE random_mvnorm(n, h, d, f, first, x, ier)
510 
511 ! Adapted from Fortran 77 code from the book:
512 ! Dagpunar, J. 'Principles of random variate generation'
513 ! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
514 
515 ! N.B. An extra argument, ier, has been added to Dagpunar's routine
516 
517 ! SUBROUTINE GENERATES AN N VARIATE RANDOM NORMAL
518 ! VECTOR USING A CHOLESKY DECOMPOSITION.
519 
520 ! ARGUMENTS:
521 ! N = NUMBER OF VARIATES IN VECTOR
522 ! (INPUT,INTEGER >= 1)
523 ! H(J) = J'TH ELEMENT OF VECTOR OF MEANS
524 ! (INPUT,REAL)
525 ! X(J) = J'TH ELEMENT OF DELIVERED VECTOR
526 ! (OUTPUT,REAL)
527 !
528 ! D(J*(J-1)/2+I) = (I,J)'TH ELEMENT OF VARIANCE MATRIX (J> = I)
529 ! (INPUT,REAL)
530 ! F((J-1)*(2*N-J)/2+I) = (I,J)'TH ELEMENT OF LOWER TRIANGULAR
531 ! DECOMPOSITION OF VARIANCE MATRIX (J <= I)
532 ! (OUTPUT,REAL)
533 
534 ! FIRST = .TRUE. IF THIS IS THE FIRST CALL OF THE ROUTINE
535 ! OR IF THE DISTRIBUTION HAS CHANGED SINCE THE LAST CALL OF THE ROUTINE.
536 ! OTHERWISE SET TO .FALSE.
537 ! (INPUT,LOGICAL)
538 
539 ! ier = 1 if the input covariance matrix is not +ve definite
540 ! = 0 otherwise
541 
542 INTEGER, INTENT(IN) :: n
543 real(kind=kind(1.0D+0)), INTENT(IN) :: h(:), d(:) ! d(n*(n+1)/2)
544 real(kind=kind(1.0D+0)), INTENT(IN OUT) :: f(:) ! f(n*(n+1)/2)
545 real(kind=kind(1.0D+0)), INTENT(OUT) :: x(:)
546 LOGICAL, INTENT(IN) :: first
547 INTEGER, INTENT(OUT) :: ier
548 
549 ! Local variables
550 INTEGER :: j, i, m
551 real(kind=kind(1.0D+0)) :: y, v
552 INTEGER, SAVE :: n2
553 
554 IF (n < 1) THEN
555  WRITE(*, *) 'SIZE OF VECTOR IS NON POSITIVE'
556  stop
557 END IF
558 
559 ier = 0
560 IF (first) THEN ! Initialization, if necessary
561  n2 = 2*n
562  IF (d(1) < zero) THEN
563  ier = 1
564  RETURN
565  END IF
566 
567  f(1) = sqrt(d(1))
568  y = one/f(1)
569  DO j = 2,n
570  f(j) = d(1+j*(j-1)/2) * y
571  END DO
572 
573  DO i = 2,n
574  v = d(i*(i-1)/2+i)
575  DO m = 1,i-1
576  v = v - f((m-1)*(n2-m)/2+i)**2
577  END DO
578 
579  IF (v < zero) THEN
580  ier = 1
581  RETURN
582  END IF
583 
584  v = sqrt(v)
585  y = one/v
586  f((i-1)*(n2-i)/2+i) = v
587  DO j = i+1,n
588  v = d(j*(j-1)/2+i)
589  DO m = 1,i-1
590  v = v - f((m-1)*(n2-m)/2+i)*f((m-1)*(n2-m)/2 + j)
591  END DO ! m = 1,i-1
592  f((i-1)*(n2-i)/2 + j) = v*y
593  END DO ! j = i+1,n
594  END DO ! i = 2,n
595 END IF
596 
597 x(1:n) = h(1:n)
598 DO j = 1,n
599  y = random_normal()
600  DO i = j,n
601  x(i) = x(i) + f((j-1)*(n2-j)/2 + i) * y
602  END DO ! i = j,n
603 END DO ! j = 1,n
604 
605 RETURN
606 END SUBROUTINE random_mvnorm
607 
608 
609 
610 FUNCTION random_inv_gauss(h, b, first) RESULT(fn_val)
611 
612 ! Adapted from Fortran 77 code from the book:
613 ! Dagpunar, J. 'Principles of random variate generation'
614 ! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
615 
616 ! FUNCTION GENERATES A RANDOM VARIATE IN [0,INFINITY] FROM
617 ! A REPARAMETERISED GENERALISED INVERSE GAUSSIAN (GIG) DISTRIBUTION
618 ! WITH DENSITY PROPORTIONAL TO GIG**(H-1) * EXP(-0.5*B*(GIG+1/GIG))
619 ! USING A RATIO METHOD.
620 
621 ! H = PARAMETER OF DISTRIBUTION (0 <= REAL)
622 ! B = PARAMETER OF DISTRIBUTION (0 < REAL)
623 
624 real(kind=kind(1.0D+0)), INTENT(IN) :: h, b
625 LOGICAL, INTENT(IN) :: first
626 real(kind=kind(1.0D+0)) :: fn_val
627 
628 ! Local variables
629 real(kind=kind(1.0D+0)) :: ym, xm, r, w, r1, r2, x
630 real(kind=kind(1.0D+0)), SAVE :: a, c, d, e
631 real(kind=kind(1.0D+0)), PARAMETER :: quart = 0.25
632 
633 IF (h < zero .OR. b <= zero) THEN
634  WRITE(*, *) 'IMPERMISSIBLE DISTRIBUTION PARAMETER VALUES'
635  stop
636 END IF
637 
638 IF (first) THEN ! Initialization, if necessary
639  IF (h > quart*b*sqrt(vlarge)) THEN
640  WRITE(*, *) 'THE RATIO H:B IS TOO SMALL'
641  stop
642  END IF
643  e = b*b
644  d = h + one
645  ym = (-d + sqrt(d*d + e))/b
646  IF (ym < vsmall) THEN
647  WRITE(*, *) 'THE VALUE OF B IS TOO SMALL'
648  stop
649  END IF
650 
651  d = h - one
652  xm = (d + sqrt(d*d + e))/b
653  d = half*d
654  e = -quart*b
655  r = xm + one/xm
656  w = xm*ym
657  a = w**(-half*h) * sqrt(xm/ym) * exp(-e*(r - ym - one/ym))
658  IF (a < vsmall) THEN
659  WRITE(*, *) 'THE VALUE OF H IS TOO LARGE'
660  stop
661  END IF
662  c = -d*log(xm) - e*r
663 END IF
664 
665 DO
666  CALL random_number(r1)
667  IF (r1 <= zero) cycle
668  CALL random_number(r2)
669  x = a*r2/r1
670  IF (x <= zero) cycle
671  IF (log(r1) < d*log(x) + e*(x + one/x) + c) EXIT
672 END DO
673 
674 fn_val = x
675 
676 RETURN
677 END FUNCTION random_inv_gauss
678 
679 
680 
681 FUNCTION random_poisson(mu, first) RESULT(ival)
682 !**********************************************************************
683 ! Translated to Fortran 90 by Alan Miller from:
684 ! RANLIB
685 !
686 ! Library of Fortran Routines for Random Number Generation
687 !
688 ! Compiled and Written by:
689 !
690 ! Barry W. Brown
691 ! James Lovato
692 !
693 ! Department of Biomathematics, Box 237
694 ! The University of Texas, M.D. Anderson Cancer Center
695 ! 1515 Holcombe Boulevard
696 ! Houston, TX 77030
697 !
698 ! This work was supported by grant CA-16672 from the National Cancer Institute.
699 
700 ! GENerate POIsson random deviate
701 
702 ! Function
703 
704 ! Generates a single random deviate from a Poisson distribution with mean mu.
705 
706 ! Arguments
707 
708 ! mu --> The mean of the Poisson distribution from which
709 ! a random deviate is to be generated.
710 ! REAL mu
711 
712 ! Method
713 
714 ! For details see:
715 
716 ! Ahrens, J.H. and Dieter, U.
717 ! Computer Generation of Poisson Deviates
718 ! From Modified Normal Distributions.
719 ! ACM Trans. Math. Software, 8, 2
720 ! (June 1982),163-179
721 
722 ! TABLES: COEFFICIENTS A0-A7 FOR STEP F. FACTORIALS FACT
723 ! COEFFICIENTS A(K) - FOR PX = FK*V*V*SUM(A(K)*V**K)-DEL
724 
725 ! SEPARATION OF CASES A AND B
726 
727 ! .. Scalar Arguments ..
728 real(kind=kind(1.0D+0)), INTENT(IN) :: mu
729 LOGICAL, INTENT(IN) :: first
730 INTEGER :: ival
731 ! ..
732 ! .. Local Scalars ..
733 real(kind=kind(1.0D+0)) :: b1, b2, c, c0, c1, c2, c3, del, difmuk, e, fk, fx, fy, g, &
734  omega, px, py, t, u, v, x, xx
735 real(kind=kind(1.0D+0)), SAVE :: s, d, p, q, p0
736 INTEGER :: j, k, kflag
737 LOGICAL, SAVE :: full_init
738 INTEGER, SAVE :: l, m
739 ! ..
740 ! .. Local Arrays ..
741 real(kind=kind(1.0D+0)), SAVE :: pp(35)
742 ! ..
743 ! .. Data statements ..
744 real(kind=kind(1.0D+0)), PARAMETER :: a0 = -.5, a1 = .3333333, a2 = -.2500068, a3 = .2000118, &
745  a4 = -.1661269, a5 = .1421878, a6 = -.1384794, &
746  a7 = .1250060
747 
748 real(kind=kind(1.0D+0)), PARAMETER :: fact(10) = (/ 1., 1., 2., 6., 24., 120., 720., 5040., &
749  40320., 362880. /)
750 
751 ! ..
752 ! .. Executable Statements ..
753 IF (mu > 10.0) THEN
754 ! C A S E A. (RECALCULATION OF S, D, L IF MU HAS CHANGED)
755 
756  IF (first) THEN
757  s = sqrt(mu)
758  d = 6.0*mu*mu
759 
760 ! THE POISSON PROBABILITIES PK EXCEED THE DISCRETE NORMAL
761 ! PROBABILITIES FK WHENEVER K >= M(MU). L=IFIX(MU-1.1484)
762 ! IS AN UPPER BOUND TO M(MU) FOR ALL MU >= 10 .
763 
764  l = mu - 1.1484
765  full_init = .false.
766  END IF
767 
768 
769 ! STEP N. NORMAL SAMPLE - random_normal() FOR STANDARD NORMAL DEVIATE
770 
771  g = mu + s*random_normal()
772  IF (g > 0.0) THEN
773  ival = g
774 
775 ! STEP I. IMMEDIATE ACCEPTANCE IF ival IS LARGE ENOUGH
776 
777  IF (ival>=l) RETURN
778 
779 ! STEP S. SQUEEZE ACCEPTANCE - SAMPLE U
780 
781  fk = ival
782  difmuk = mu - fk
783  CALL random_number(u)
784  IF (d*u >= difmuk*difmuk*difmuk) RETURN
785  END IF
786 
787 ! STEP P. PREPARATIONS FOR STEPS Q AND H.
788 ! (RECALCULATIONS OF PARAMETERS IF NECESSARY)
789 ! .3989423=(2*PI)**(-.5) .416667E-1=1./24. .1428571=1./7.
790 ! THE QUANTITIES B1, B2, C3, C2, C1, C0 ARE FOR THE HERMITE
791 ! APPROXIMATIONS TO THE DISCRETE NORMAL PROBABILITIES FK.
792 ! C=.1069/MU GUARANTEES MAJORIZATION BY THE 'HAT'-FUNCTION.
793 
794  IF (.NOT. full_init) THEN
795  omega = .3989423/s
796  b1 = .4166667e-1/mu
797  b2 = .3*b1*b1
798  c3 = .1428571*b1*b2
799  c2 = b2 - 15.*c3
800  c1 = b1 - 6.*b2 + 45.*c3
801  c0 = 1. - b1 + 3.*b2 - 15.*c3
802  c = .1069/mu
803  full_init = .true.
804  END IF
805 
806  IF (g < 0.0) go to 50
807 
808 ! 'SUBROUTINE' F IS CALLED (KFLAG=0 FOR CORRECT RETURN)
809 
810  kflag = 0
811  go to 70
812 
813 ! STEP Q. QUOTIENT ACCEPTANCE (RARE CASE)
814 
815  40 IF (fy-u*fy <= py*exp(px-fx)) RETURN
816 
817 ! STEP E. EXPONENTIAL SAMPLE - random_exponential() FOR STANDARD EXPONENTIAL
818 ! DEVIATE E AND SAMPLE T FROM THE LAPLACE 'HAT'
819 ! (IF T <= -.6744 THEN PK < FK FOR ALL MU >= 10.)
820 
821  50 e = random_exponential()
822  CALL random_number(u)
823  u = u + u - one
824  t = 1.8 + sign(e, u)
825  IF (t <= (-.6744)) go to 50
826  ival = mu + s*t
827  fk = ival
828  difmuk = mu - fk
829 
830 ! 'SUBROUTINE' F IS CALLED (KFLAG=1 FOR CORRECT RETURN)
831 
832  kflag = 1
833  go to 70
834 
835 ! STEP H. HAT ACCEPTANCE (E IS REPEATED ON REJECTION)
836 
837  60 IF (c*abs(u) > py*exp(px+e) - fy*exp(fx+e)) go to 50
838  RETURN
839 
840 ! STEP F. 'SUBROUTINE' F. CALCULATION OF PX, PY, FX, FY.
841 ! CASE ival < 10 USES FACTORIALS FROM TABLE FACT
842 
843  70 IF (ival>=10) go to 80
844  px = -mu
845  py = mu**ival/fact(ival+1)
846  go to 110
847 
848 ! CASE ival >= 10 USES POLYNOMIAL APPROXIMATION
849 ! A0-A7 FOR ACCURACY WHEN ADVISABLE
850 ! .8333333E-1=1./12. .3989423=(2*PI)**(-.5)
851 
852  80 del = .8333333e-1/fk
853  del = del - 4.8*del*del*del
854  v = difmuk/fk
855  IF (abs(v)>0.25) THEN
856  px = fk*log(one + v) - difmuk - del
857  ELSE
858  px = fk*v*v* (((((((a7*v+a6)*v+a5)*v+a4)*v+a3)*v+a2)*v+a1)*v+a0) - del
859  END IF
860  py = .3989423/sqrt(fk)
861  110 x = (half - difmuk)/s
862  xx = x*x
863  fx = -half*xx
864  fy = omega* (((c3*xx + c2)*xx + c1)*xx + c0)
865  IF (kflag <= 0) go to 40
866  go to 60
867 
868 !---------------------------------------------------------------------------
869 ! C A S E B. mu < 10
870 ! START NEW TABLE AND CALCULATE P0 IF NECESSARY
871 
872 ELSE
873  IF (first) THEN
874  m = max(1, int(mu))
875  l = 0
876  p = exp(-mu)
877  q = p
878  p0 = p
879  END IF
880 
881 ! STEP U. UNIFORM SAMPLE FOR INVERSION METHOD
882 
883  DO
884  CALL random_number(u)
885  ival = 0
886  IF (u <= p0) RETURN
887 
888 ! STEP T. TABLE COMPARISON UNTIL THE END PP(L) OF THE
889 ! PP-TABLE OF CUMULATIVE POISSON PROBABILITIES
890 ! (0.458=PP(9) FOR MU=10)
891 
892  IF (l == 0) go to 150
893  j = 1
894  IF (u > 0.458) j = min(l, m)
895  DO k = j, l
896  IF (u <= pp(k)) go to 180
897  END DO
898  IF (l == 35) cycle
899 
900 ! STEP C. CREATION OF NEW POISSON PROBABILITIES P
901 ! AND THEIR CUMULATIVES Q=PP(K)
902 
903  150 l = l + 1
904  DO k = l, 35
905  p = p*mu / k
906  q = q + p
907  pp(k) = q
908  IF (u <= q) go to 170
909  END DO
910  l = 35
911  END DO
912 
913  170 l = k
914  180 ival = k
915  RETURN
916 END IF
917 
918 RETURN
919 END FUNCTION random_poisson
920 
921 
922 
923 FUNCTION random_binomial1(n, p, first) RESULT(ival)
924 
925 ! FUNCTION GENERATES A RANDOM BINOMIAL VARIATE USING C.D.Kemp's method.
926 ! This algorithm is suitable when many random variates are required
927 ! with the SAME parameter values for n & p.
928 
929 ! P = BERNOULLI SUCCESS PROBABILITY
930 ! (0 <= REAL <= 1)
931 ! N = NUMBER OF BERNOULLI TRIALS
932 ! (1 <= INTEGER)
933 ! FIRST = .TRUE. for the first call using the current parameter values
934 ! = .FALSE. if the values of (n,p) are unchanged from last call
935 
936 ! Reference: Kemp, C.D. (1986). `A modal method for generating binomial
937 ! variables', Commun. Statist. - Theor. Meth. 15(3), 805-813.
938 
939 INTEGER, INTENT(IN) :: n
940 real(kind=kind(1.0D+0)), INTENT(IN) :: p
941 LOGICAL, INTENT(IN) :: first
942 INTEGER :: ival
943 
944 ! Local variables
945 
946 INTEGER :: ru, rd
947 INTEGER, SAVE :: r0
948 real(kind=kind(1.0D+0)) :: u, pd, pu
949 real(kind=kind(1.0D+0)), SAVE :: odds_ratio, p_r
950 real(kind=kind(1.0D+0)), PARAMETER :: zero = 0.0, one = 1.0
951 
952 IF (first) THEN
953  r0 = (n+1)*p
954  p_r = bin_prob(n, p, r0)
955  odds_ratio = p / (one - p)
956 END IF
957 
958 CALL random_number(u)
959 u = u - p_r
960 IF (u < zero) THEN
961  ival = r0
962  RETURN
963 END IF
964 
965 pu = p_r
966 ru = r0
967 pd = p_r
968 rd = r0
969 DO
970  rd = rd - 1
971  IF (rd >= 0) THEN
972  pd = pd * (rd+1) / (odds_ratio * (n-rd))
973  u = u - pd
974  IF (u < zero) THEN
975  ival = rd
976  RETURN
977  END IF
978  END IF
979 
980  ru = ru + 1
981  IF (ru <= n) THEN
982  pu = pu * (n-ru+1) * odds_ratio / ru
983  u = u - pu
984  IF (u < zero) THEN
985  ival = ru
986  RETURN
987  END IF
988  END IF
989 END DO
990 
991 ! This point should not be reached, but just in case:
992 
993 ival = r0
994 RETURN
995 
996 END FUNCTION random_binomial1
997 
998 
999 
1000 FUNCTION bin_prob(n, p, r) RESULT(fn_val)
1001 ! Calculate a binomial probability
1002 
1003 INTEGER, INTENT(IN) :: n, r
1004 real(kind=kind(1.0D+0)), INTENT(IN) :: p
1005 real(kind=kind(1.0D+0)) :: fn_val
1006 
1007 ! Local variable
1008 real(kind=kind(1.0D+0)) :: one = 1.0
1009 
1010 fn_val = exp( lngamma(dble(n+1)) - lngamma(dble(r+1)) - lngamma(dble(n-r+1)) &
1011  + r*log(p) + (n-r)*log(one - p) )
1012 RETURN
1013 
1014 END FUNCTION bin_prob
1015 
1016 
1017 
1018 FUNCTION lngamma(x) RESULT(fn_val)
1019 
1020 ! Logarithm to base e of the gamma function.
1021 !
1022 ! Accurate to about 1.e-14.
1023 ! Programmer: Alan Miller
1024 
1025 ! Latest revision of Fortran 77 version - 28 February 1988
1026 
1027 REAL (dp), INTENT(IN) :: x
1028 REAL (dp) :: fn_val
1029 
1030 ! Local variables
1031 
1032 REAL (dp) :: a1 = -4.166666666554424D-02, a2 = 2.430554511376954D-03, &
1033  a3 = -7.685928044064347D-04, a4 = 5.660478426014386D-04, &
1034  temp, arg, product, lnrt2pi = 9.189385332046727D-1, &
1035  pi = 3.141592653589793D0
1036 LOGICAL :: reflect
1037 
1038 ! lngamma is not defined if x = 0 or a negative integer.
1039 
1040 IF (x > 0.d0) go to 10
1041 IF (x /= int(x)) go to 10
1042 fn_val = 0.d0
1043 RETURN
1044 
1045 ! If x < 0, use the reflection formula:
1046 ! gamma(x) * gamma(1-x) = pi * cosec(pi.x)
1047 
1048 10 reflect = (x < 0.d0)
1049 IF (reflect) THEN
1050  arg = 1.d0 - x
1051 ELSE
1052  arg = x
1053 END IF
1054 
1055 ! Increase the argument, if necessary, to make it > 10.
1056 
1057 product = 1.d0
1058 20 IF (arg <= 10.d0) THEN
1059  product = product * arg
1060  arg = arg + 1.d0
1061  go to 20
1062 END IF
1063 
1064 ! Use a polynomial approximation to Stirling's formula.
1065 ! N.B. The real Stirling's formula is used here, not the simpler, but less
1066 ! accurate formula given by De Moivre in a letter to Stirling, which
1067 ! is the one usually quoted.
1068 
1069 arg = arg - 0.5d0
1070 temp = 1.d0/arg**2
1071 fn_val = lnrt2pi + arg * (log(arg) - 1.d0 + &
1072  (((a4*temp + a3)*temp + a2)*temp + a1)*temp) - log(product)
1073 IF (reflect) THEN
1074  temp = sin(pi * x)
1075  fn_val = log(pi/temp) - fn_val
1076 END IF
1077 RETURN
1078 END FUNCTION lngamma
1079 
1080 
1081 
1082 FUNCTION random_binomial2(n, pp, first) RESULT(ival)
1083 !**********************************************************************
1084 ! Translated to Fortran 90 by Alan Miller from:
1085 ! RANLIB
1086 !
1087 ! Library of Fortran Routines for Random Number Generation
1088 !
1089 ! Compiled and Written by:
1090 !
1091 ! Barry W. Brown
1092 ! James Lovato
1093 !
1094 ! Department of Biomathematics, Box 237
1095 ! The University of Texas, M.D. Anderson Cancer Center
1096 ! 1515 Holcombe Boulevard
1097 ! Houston, TX 77030
1098 !
1099 ! This work was supported by grant CA-16672 from the National Cancer Institute.
1100 
1101 ! GENerate BINomial random deviate
1102 
1103 ! Function
1104 
1105 ! Generates a single random deviate from a binomial
1106 ! distribution whose number of trials is N and whose
1107 ! probability of an event in each trial is P.
1108 
1109 ! Arguments
1110 
1111 ! N --> The number of trials in the binomial distribution
1112 ! from which a random deviate is to be generated.
1113 ! INTEGER N
1114 
1115 ! P --> The probability of an event in each trial of the
1116 ! binomial distribution from which a random deviate
1117 ! is to be generated.
1118 ! REAL P
1119 
1120 ! FIRST --> Set FIRST = .TRUE. for the first call to perform initialization
1121 ! the set FIRST = .FALSE. for further calls using the same pair
1122 ! of parameter values (N, P).
1123 ! LOGICAL FIRST
1124 
1125 ! random_binomial2 <-- A random deviate yielding the number of events
1126 ! from N independent trials, each of which has
1127 ! a probability of event P.
1128 ! INTEGER random_binomial
1129 
1130 ! Method
1131 
1132 ! This is algorithm BTPE from:
1133 
1134 ! Kachitvichyanukul, V. and Schmeiser, B. W.
1135 ! Binomial Random Variate Generation.
1136 ! Communications of the ACM, 31, 2 (February, 1988) 216.
1137 
1138 !**********************************************************************
1139 
1140 !*****DETERMINE APPROPRIATE ALGORITHM AND WHETHER SETUP IS NECESSARY
1141 
1142 ! ..
1143 ! .. Scalar Arguments ..
1144 real(kind=kind(1.0D+0)), INTENT(IN) :: pp
1145 INTEGER, INTENT(IN) :: n
1146 LOGICAL, INTENT(IN) :: first
1147 INTEGER :: ival
1148 ! ..
1149 ! .. Local Scalars ..
1150 real(kind=kind(1.0D+0)) :: alv, amaxp, f, f1, f2, u, v, w, w2, x, x1, x2, ynorm, z, z2
1151 real(kind=kind(1.0D+0)), PARAMETER :: zero = 0.0, half = 0.5, one = 1.0
1152 INTEGER :: i, ix, ix1, k, mp
1153 INTEGER, SAVE :: m
1154 real(kind=kind(1.0D+0)), SAVE :: p, q, xnp, ffm, fm, xnpq, p1, xm, xl, xr, c, al, xll, &
1155  xlr, p2, p3, p4, qn, r, g
1156 
1157 ! ..
1158 ! .. Executable Statements ..
1159 
1160 !*****SETUP, PERFORM ONLY WHEN PARAMETERS CHANGE
1161 
1162 IF (first) THEN
1163  p = min(pp, one-pp)
1164  q = one - p
1165  xnp = n * p
1166 END IF
1167 
1168 IF (xnp > 30.) THEN
1169  IF (first) THEN
1170  ffm = xnp + p
1171  m = ffm
1172  fm = m
1173  xnpq = xnp * q
1174  p1 = int(2.195*sqrt(xnpq) - 4.6*q) + half
1175  xm = fm + half
1176  xl = xm - p1
1177  xr = xm + p1
1178  c = 0.134 + 20.5 / (15.3 + fm)
1179  al = (ffm-xl) / (ffm - xl*p)
1180  xll = al * (one + half*al)
1181  al = (xr - ffm) / (xr*q)
1182  xlr = al * (one + half*al)
1183  p2 = p1 * (one + c + c)
1184  p3 = p2 + c / xll
1185  p4 = p3 + c / xlr
1186  END IF
1187 
1188 !*****GENERATE VARIATE, Binomial mean at least 30.
1189 
1190  20 CALL random_number(u)
1191  u = u * p4
1192  CALL random_number(v)
1193 
1194 ! TRIANGULAR REGION
1195 
1196  IF (u <= p1) THEN
1197  ix = xm - p1 * v + u
1198  go to 110
1199  END IF
1200 
1201 ! PARALLELOGRAM REGION
1202 
1203  IF (u <= p2) THEN
1204  x = xl + (u-p1) / c
1205  v = v * c + one - abs(xm-x) / p1
1206  IF (v > one .OR. v <= zero) go to 20
1207  ix = x
1208  ELSE
1209 
1210 ! LEFT TAIL
1211 
1212  IF (u <= p3) THEN
1213  ix = xl + log(v) / xll
1214  IF (ix < 0) go to 20
1215  v = v * (u-p2) * xll
1216  ELSE
1217 
1218 ! RIGHT TAIL
1219 
1220  ix = xr - log(v) / xlr
1221  IF (ix > n) go to 20
1222  v = v * (u-p3) * xlr
1223  END IF
1224  END IF
1225 
1226 !*****DETERMINE APPROPRIATE WAY TO PERFORM ACCEPT/REJECT TEST
1227 
1228  k = abs(ix-m)
1229  IF (k <= 20 .OR. k >= xnpq/2-1) THEN
1230 
1231 ! EXPLICIT EVALUATION
1232 
1233  f = one
1234  r = p / q
1235  g = (n+1) * r
1236  IF (m < ix) THEN
1237  mp = m + 1
1238  DO i = mp, ix
1239  f = f * (g/i-r)
1240  END DO
1241 
1242  ELSE IF (m > ix) THEN
1243  ix1 = ix + 1
1244  DO i = ix1, m
1245  f = f / (g/i-r)
1246  END DO
1247  END IF
1248 
1249  IF (v > f) THEN
1250  go to 20
1251  ELSE
1252  go to 110
1253  END IF
1254  END IF
1255 
1256 ! SQUEEZING USING UPPER AND LOWER BOUNDS ON LOG(F(X))
1257 
1258  amaxp = (k/xnpq) * ((k*(k/3. + .625) + .1666666666666)/xnpq + half)
1259  ynorm = -k * k / (2.*xnpq)
1260  alv = log(v)
1261  IF (alv<ynorm - amaxp) go to 110
1262  IF (alv>ynorm + amaxp) go to 20
1263 
1264 ! STIRLING'S (actually de Moivre's) FORMULA TO MACHINE ACCURACY FOR
1265 ! THE FINAL ACCEPTANCE/REJECTION TEST
1266 
1267  x1 = ix + 1
1268  f1 = fm + one
1269  z = n + 1 - fm
1270  w = n - ix + one
1271  z2 = z * z
1272  x2 = x1 * x1
1273  f2 = f1 * f1
1274  w2 = w * w
1275  IF (alv - (xm*log(f1/x1) + (n-m+half)*log(z/w) + (ix-m)*log(w*p/(x1*q)) + &
1276  (13860.-(462.-(132.-(99.-140./f2)/f2)/f2)/f2)/f1/166320. + &
1277  (13860.-(462.-(132.-(99.-140./z2)/z2)/z2)/z2)/z/166320. + &
1278  (13860.-(462.-(132.-(99.-140./x2)/x2)/x2)/x2)/x1/166320. + &
1279  (13860.-(462.-(132.-(99.-140./w2)/w2)/w2)/w2)/w/166320.) > zero) THEN
1280  go to 20
1281  ELSE
1282  go to 110
1283  END IF
1284 
1285 ELSE
1286 ! INVERSE CDF LOGIC FOR MEAN LESS THAN 30
1287  IF (first) THEN
1288  qn = q ** n
1289  r = p / q
1290  g = r * (n+1)
1291  END IF
1292 
1293  90 ix = 0
1294  f = qn
1295  CALL random_number(u)
1296  100 IF (u >= f) THEN
1297  IF (ix > 110) go to 90
1298  u = u - f
1299  ix = ix + 1
1300  f = f * (g/ix - r)
1301  go to 100
1302  END IF
1303 END IF
1304 
1305 110 IF (pp > half) ix = n - ix
1306 ival = ix
1307 RETURN
1308 
1309 END FUNCTION random_binomial2
1310 
1311 
1312 
1313 
1314 FUNCTION random_neg_binomial(sk, p) RESULT(ival)
1315 
1316 ! Adapted from Fortran 77 code from the book:
1317 ! Dagpunar, J. 'Principles of random variate generation'
1318 ! Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9
1319 
1320 ! FUNCTION GENERATES A RANDOM NEGATIVE BINOMIAL VARIATE USING UNSTORED
1321 ! INVERSION AND/OR THE REPRODUCTIVE PROPERTY.
1322 
1323 ! SK = NUMBER OF FAILURES REQUIRED (Dagpunar's words!)
1324 ! = the `power' parameter of the negative binomial
1325 ! (0 < REAL)
1326 ! P = BERNOULLI SUCCESS PROBABILITY
1327 ! (0 < REAL < 1)
1328 
1329 ! THE PARAMETER H IS SET SO THAT UNSTORED INVERSION ONLY IS USED WHEN P <= H,
1330 ! OTHERWISE A COMBINATION OF UNSTORED INVERSION AND
1331 ! THE REPRODUCTIVE PROPERTY IS USED.
1332 
1333 real(kind=kind(1.0D+0)), INTENT(IN) :: sk, p
1334 INTEGER :: ival
1335 
1336 ! Local variables
1337 ! THE PARAMETER ULN = -LOG(MACHINE'S SMALLEST REAL NUMBER).
1338 
1339 real(kind=kind(1.0D+0)), PARAMETER :: h = 0.7
1340 real(kind=kind(1.0D+0)) :: q, x, st, uln, v, r, s, y, g
1341 INTEGER :: k, i, n
1342 
1343 IF (sk <= zero .OR. p <= zero .OR. p >= one) THEN
1344  WRITE(*, *) 'IMPERMISSIBLE DISTRIBUTION PARAMETER VALUES'
1345  stop
1346 END IF
1347 
1348 q = one - p
1349 x = zero
1350 st = sk
1351 IF (p > h) THEN
1352  v = one/log(p)
1353  k = st
1354  DO i = 1,k
1355  DO
1356  CALL random_number(r)
1357  IF (r > zero) EXIT
1358  END DO
1359  n = v*log(r)
1360  x = x + n
1361  END DO
1362  st = st - k
1363 END IF
1364 
1365 s = zero
1366 uln = -log(vsmall)
1367 IF (st > -uln/log(q)) THEN
1368  WRITE(*, *) ' P IS TOO LARGE FOR THIS VALUE OF SK'
1369  stop
1370 END IF
1371 
1372 y = q**st
1373 g = st
1374 CALL random_number(r)
1375 DO
1376  IF (y > r) EXIT
1377  r = r - y
1378  s = s + one
1379  y = y*p*g/s
1380  g = g + one
1381 END DO
1382 
1383 ival = x + s + half
1384 RETURN
1385 END FUNCTION random_neg_binomial
1386 
1387 
1388 
1389 FUNCTION random_von_mises(k, first) RESULT(fn_val)
1390 
1391 ! Algorithm VMD from:
1392 ! Dagpunar, J.S. (1990) `Sampling from the von Mises distribution via a
1393 ! comparison of random numbers', J. of Appl. Statist., 17, 165-168.
1394 
1395 ! Fortran 90 code by Alan Miller
1396 ! CSIRO Division of Mathematical & Information Sciences
1397 
1398 ! Arguments:
1399 ! k (real) parameter of the von Mises distribution.
1400 ! first (logical) set to .TRUE. the first time that the function
1401 ! is called, or the first time with a new value
1402 ! for k. When first = .TRUE., the function sets
1403 ! up starting values and may be very much slower.
1404 
1405 real(kind=kind(1.0D+0)), INTENT(IN) :: k
1406 LOGICAL, INTENT(IN) :: first
1407 real(kind=kind(1.0D+0)) :: fn_val
1408 
1409 ! Local variables
1410 
1411 INTEGER :: j, n
1412 INTEGER, SAVE :: nk
1413 real(kind=kind(1.0D+0)), PARAMETER :: pi = 3.14159265
1414 real(kind=kind(1.0D+0)), SAVE :: p(20), theta(0:20)
1415 real(kind=kind(1.0D+0)) :: sump, r, th, lambda, rlast
1416 REAL (dp) :: dk
1417 
1418 IF (first) THEN ! Initialization, if necessary
1419  IF (k < zero) THEN
1420  WRITE(*, *) '** Error: argument k for random_von_Mises = ', k
1421  RETURN
1422  END IF
1423 
1424  nk = k + k + one
1425  IF (nk > 20) THEN
1426  WRITE(*, *) '** Error: argument k for random_von_Mises = ', k
1427  RETURN
1428  END IF
1429 
1430  dk = k
1431  theta(0) = zero
1432  IF (k > half) THEN
1433 
1434 ! Set up array p of probabilities.
1435 
1436  sump = zero
1437  DO j = 1, nk
1438  IF (j < nk) THEN
1439  theta(j) = acos(one - j/k)
1440  ELSE
1441  theta(nk) = pi
1442  END IF
1443 
1444 ! Numerical integration of e^[k.cos(x)] from theta(j-1) to theta(j)
1445 
1446  CALL integral(theta(j-1), theta(j), p(j), dk)
1447  sump = sump + p(j)
1448  END DO
1449  p(1:nk) = p(1:nk) / sump
1450  ELSE
1451  p(1) = one
1452  theta(1) = pi
1453  END IF ! if k > 0.5
1454 END IF ! if first
1455 
1456 CALL random_number(r)
1457 DO j = 1, nk
1458  r = r - p(j)
1459  IF (r < zero) EXIT
1460 END DO
1461 r = -r/p(j)
1462 
1463 DO
1464  th = theta(j-1) + r*(theta(j) - theta(j-1))
1465  lambda = k - j + one - k*cos(th)
1466  n = 1
1467  rlast = lambda
1468 
1469  DO
1470  CALL random_number(r)
1471  IF (r > rlast) EXIT
1472  n = n + 1
1473  rlast = r
1474  END DO
1475 
1476  IF (n .NE. 2*(n/2)) EXIT ! is n even?
1477  CALL random_number(r)
1478 END DO
1479 
1480 fn_val = sign(th, (r - rlast)/(one - rlast) - half)
1481 RETURN
1482 END FUNCTION random_von_mises
1483 
1484 
1485 
1486 SUBROUTINE integral(a, b, result, dk)
1487 
1488 ! Gaussian integration of exp(k.cosx) from a to b.
1489 
1490 REAL (dp), INTENT(IN) :: dk
1491 real(kind=kind(1.0D+0)), INTENT(IN) :: a, b
1492 real(kind=kind(1.0D+0)), INTENT(OUT) :: result
1493 
1494 ! Local variables
1495 
1496 REAL (dp) :: xmid, range, x1, x2, &
1497  x(3) = (/0.238619186083197_dp, 0.661209386466265_dp, 0.932469514203152_dp/), &
1498  w(3) = (/0.467913934572691_dp, 0.360761573048139_dp, 0.171324492379170_dp/)
1499 INTEGER :: i
1500 
1501 xmid = (a + b)/2._dp
1502 range = (b - a)/2._dp
1503 
1504 result = 0._dp
1505 DO i = 1, 3
1506  x1 = xmid + x(i)*range
1507  x2 = xmid - x(i)*range
1508  result = result + w(i)*(exp(dk*cos(x1)) + exp(dk*cos(x2)))
1509 END DO
1510 
1511 result = result * range
1512 RETURN
1513 END SUBROUTINE integral
1514 
1515 
1516 
1517 FUNCTION random_cauchy() RESULT(fn_val)
1518 
1519 ! Generate a random deviate from the standard Cauchy distribution
1520 
1521 real(kind=kind(1.0D+0)) :: fn_val
1522 
1523 ! Local variables
1524 real(kind=kind(1.0D+0)) :: v(2)
1525 
1526 DO
1527  CALL random_number(v)
1528  v = two*(v - half)
1529  IF (abs(v(2)) < vsmall) cycle ! Test for zero
1530  IF (v(1)**2 + v(2)**2 < one) EXIT
1531 END DO
1532 fn_val = v(1) / v(2)
1533 
1534 RETURN
1535 END FUNCTION random_cauchy
1536 
1537 
1538 
1539 SUBROUTINE random_order(order, n)
1540 
1541 ! Generate a random ordering of the integers 1 ... n.
1542 
1543 INTEGER, INTENT(IN) :: n
1544 INTEGER, INTENT(OUT) :: order(n)
1545 
1546 ! Local variables
1547 
1548 INTEGER :: i, j, k
1549 real(kind=kind(1.0D+0)) :: wk
1550 
1551 DO i = 1, n
1552  order(i) = i
1553 END DO
1554 
1555 ! Starting at the end, swap the current last indicator with one
1556 ! randomly chosen from those preceeding it.
1557 
1558 DO i = n, 2, -1
1559  CALL random_number(wk)
1560  j = 1 + i * wk
1561  IF (j < i) THEN
1562  k = order(i)
1563  order(i) = order(j)
1564  order(j) = k
1565  END IF
1566 END DO
1567 
1568 RETURN
1569 END SUBROUTINE random_order
1570 
1571 
1572 
1573 SUBROUTINE seed_random_number(iounit)
1574 
1575 INTEGER, INTENT(IN) :: iounit
1576 
1577 ! Local variables
1578 
1579 INTEGER :: k
1580 INTEGER, ALLOCATABLE :: seed(:)
1581 
1582 CALL random_seed(size=k)
1583 ALLOCATE( seed(k) )
1584 
1585 WRITE(*, '(a, i2, a)')' Enter ', k, ' integers for random no. seeds: '
1586 READ(*, *) seed
1587 WRITE(iounit, '(a, (7i10))') ' Random no. seeds: ', seed
1588 CALL random_seed(put=seed)
1589 
1590 DEALLOCATE( seed )
1591 
1592 RETURN
1593 END SUBROUTINE seed_random_number
1594 
1595 
1596 END MODULE random
real(kind=kind(1.0d+0)) function random_gamma2(s, first)
Definition: random_d.f90:238
real(kind=kind(1.0d+0)) function random_von_mises(k, first)
Definition: random_d.f90:1389
real(kind=kind(1.0d+0)) function random_weibull(a)
Definition: random_d.f90:351
subroutine random_mvnorm(n, h, d, f, first, x, ier)
Definition: random_d.f90:509
integer function random_neg_binomial(sk, p)
Definition: random_d.f90:1314
real(kind=kind(1.0d+0)) function random_chisq(ndf, first)
Definition: random_d.f90:308
real(kind=kind(1.0d+0)) function random_exponential()
Definition: random_d.f90:324
real(dp) function lngamma(x)
Definition: random_d.f90:1018
real(kind=kind(1.0d+0)) function bin_prob(n, p, r)
Definition: random_d.f90:1000
subroutine random_order(order, n)
Definition: random_d.f90:1539
real(kind=kind(1.0d+0)) function random_t(m)
Definition: random_d.f90:448
integer function random_poisson(mu, first)
Definition: random_d.f90:681
subroutine seed_random_number(iounit)
Definition: random_d.f90:1573
integer function random_binomial2(n, pp, first)
Definition: random_d.f90:1082
real(kind=kind(1.0d+0)) function random_gamma(s, first)
Definition: random_d.f90:154
real(kind=kind(1.0d+0)) function random_inv_gauss(h, b, first)
Definition: random_d.f90:610
real(kind=kind(1.0d+0)) function random_gamma1(s, first)
Definition: random_d.f90:189
real(kind=kind(1.0d+0)) function random_cauchy()
Definition: random_d.f90:1517
real(kind=kind(1.0d+0)) function random_normal()
function to get random normal with zero mean and stdev 1
Definition: random_d.f90:108
A module for random number generation from the following distributions:
Definition: random_d.f90:22
real(kind=kind(1.0d+0)) function random_beta(aa, bb, first)
Definition: random_d.f90:371
integer function random_binomial1(n, p, first)
Definition: random_d.f90:923