*-----------------------------------------------------------------------
* codd - coefficient of determination, double precision
* by Andy Allinger, 2018-2025, released to the public domain
*
*    Permission  to  use, copy, modify, and distribute this software and
*    its documentation  for  any  purpose  and  without  fee  is  hereby
*    granted,  without any conditions or restrictions.  This software is
*    provided "as is" without express or implied warranty.
*
*___Name_______Type______In/Out___Description___________________________
*   N          Integer   In       Number of instances
*   Y(N)       Double    In       Correct answers
*   Z(N)       Double    In       Predictions
*   RESULT     Double    Out      Coefficient of determination
*-----------------------------------------------------------------------
      SUBROUTINE CODD (N, Y, Z, RESULT)
       IMPLICIT NONE
       INTEGER N
       DOUBLE PRECISION Y(N), Z(N), RESULT

       DOUBLE PRECISION ZERO, ONE
       PARAMETER (ZERO = 0.D0,
     $            ONE = 1.D0)
       INTEGER I
       DOUBLE PRECISION RESID, SOS, YAVE
       LOGICAL DAFDIV                            ! external function
       
*-----------------------------------------------------------------------
*          Begin.  
*-----------------------------------------------------------------------
       RESULT = ZERO
       IF (N < 1) RETURN
       YAVE = ZERO                               ! average
       DO I = 1, N
         YAVE = YAVE + Y(I)
       END DO
       YAVE = YAVE / DBLE(N)
       
       SOS = ZERO                              
       RESID = ZERO
       DO I = 1, N
         SOS = SOS + (Y(I) - YAVE)**2            ! total variation
         RESID = RESID + (Z(I) - Y(I))**2        ! residual
       END DO       
       IF (DAFDIV(RESID, SOS)) RESULT = ONE - RESID / SOS
       
       RETURN
      END  ! of codd
