OpenLibm/slatec/dbinom.f
Viral B. Shah c977aa998f Add Makefile.extras to build libopenlibm-extras.
Replace amos with slatec
2012-12-31 16:37:05 -05:00

75 lines
2.4 KiB
Fortran

*DECK DBINOM
DOUBLE PRECISION FUNCTION DBINOM (N, M)
C***BEGIN PROLOGUE DBINOM
C***PURPOSE Compute the binomial coefficients.
C***LIBRARY SLATEC (FNLIB)
C***CATEGORY C1
C***TYPE DOUBLE PRECISION (BINOM-S, DBINOM-D)
C***KEYWORDS BINOMIAL COEFFICIENTS, FNLIB, SPECIAL FUNCTIONS
C***AUTHOR Fullerton, W., (LANL)
C***DESCRIPTION
C
C DBINOM(N,M) calculates the double precision binomial coefficient
C for integer arguments N and M. The result is (N!)/((M!)(N-M)!).
C
C***REFERENCES (NONE)
C***ROUTINES CALLED D1MACH, D9LGMC, DLNREL, XERMSG
C***REVISION HISTORY (YYMMDD)
C 770601 DATE WRITTEN
C 890531 Changed all specific intrinsics to generic. (WRB)
C 890531 REVISION DATE from Version 3.2
C 891214 Prologue converted to Version 4.0 format. (BAB)
C 900315 CALLs to XERROR changed to CALLs to XERMSG. (THJ)
C***END PROLOGUE DBINOM
DOUBLE PRECISION CORR, FINTMX, SQ2PIL, XK, XN, XNK, D9LGMC,
1 DLNREL, D1MACH, BILNMX
LOGICAL FIRST
SAVE SQ2PIL, BILNMX, FINTMX, FIRST
DATA SQ2PIL / 0.9189385332 0467274178 0329736405 62 D0 /
DATA FIRST /.TRUE./
C***FIRST EXECUTABLE STATEMENT DBINOM
IF (FIRST) THEN
BILNMX = LOG(D1MACH(2)) - 0.0001D0
FINTMX = 0.9D0/D1MACH(3)
ENDIF
FIRST = .FALSE.
C
IF (N .LT. 0 .OR. M .LT. 0) CALL XERMSG ('SLATEC', 'DBINOM',
+ 'N OR M LT ZERO', 1, 2)
IF (N .LT. M) CALL XERMSG ('SLATEC', 'DBINOM', 'N LT M', 2, 2)
C
K = MIN (M, N-M)
IF (K.GT.20) GO TO 30
IF (K*LOG(AMAX0(N,1)).GT.BILNMX) GO TO 30
C
DBINOM = 1.0D0
IF (K.EQ.0) RETURN
DO 20 I=1,K
XN = N - I + 1
XK = I
DBINOM = DBINOM * (XN/XK)
20 CONTINUE
C
IF (DBINOM.LT.FINTMX) DBINOM = AINT (DBINOM+0.5D0)
RETURN
C
C IF K.LT.9, APPROX IS NOT VALID AND ANSWER IS CLOSE TO THE OVERFLOW LIM
30 IF (K .LT. 9) CALL XERMSG ('SLATEC', 'DBINOM',
+ 'RESULT OVERFLOWS BECAUSE N AND/OR M TOO BIG', 3, 2)
C
XN = N + 1
XK = K + 1
XNK = N - K + 1
C
CORR = D9LGMC(XN) - D9LGMC(XK) - D9LGMC(XNK)
DBINOM = XK*LOG(XNK/XK) - XN*DLNREL(-(XK-1.0D0)/XN)
1 -0.5D0*LOG(XN*XNK/XK) + 1.0D0 - SQ2PIL + CORR
C
IF (DBINOM .GT. BILNMX) CALL XERMSG ('SLATEC', 'DBINOM',
+ 'RESULT OVERFLOWS BECAUSE N AND/OR M TOO BIG', 3, 2)
C
DBINOM = EXP (DBINOM)
IF (DBINOM.LT.FINTMX) DBINOM = AINT (DBINOM+0.5D0)
C
RETURN
END