! Example 4.23. Statistics with covariance and correlation.
  module E23M
    implicit none
    public :: Tally, Report
    integer, save, public :: How_Many = 0
    integer, parameter, private :: K = selected_real_kind( 6 )
    real(kind = K), public :: X, Y, X_Mean, Y_Mean, X_Dev, Y_Dev, Covar, Correlation, A, B
    real(kind = K), save, private :: X_Sum = 0.0_K, Y_Sum = 0.0_K, &
      XX_Sum = 0.0_K, YY_Sum = 0.0_K, XY_Sum = 0.0_K
  contains
    subroutine Tally( )
      How_Many = How_Many + 1
      X_Sum = X_Sum + X
      Y_Sum = Y_Sum + Y
      XX_Sum = XX_Sum + X ** 2
      YY_Sum = YY_Sum + Y ** 2
      XY_Sum = XY_Sum + X * Y
      return
    end subroutine Tally
    subroutine Report( )
      if (How_Many > 0) then
        X_Mean = X_Sum / real( How_Many )
        Y_Mean = Y_Sum / real( How_Many )
        if (How_Many > 1) then
          X_Dev = sqrt( (XX_Sum / real( How_Many )) - X_Mean ** 2 )
          Y_Dev = sqrt( (YY_Sum / real( How_Many )) - Y_Mean ** 2 )
          Covar = (XY_Sum / real( How_Many )) - X_Mean * Y_Mean
          Correlation = Covar / (X_Dev * Y_Dev)
          B = Covar / X_Dev ** 2
          A = Y_Mean - B * X_Mean
        end if
      end if
      return
    end subroutine Report
  end module E23M
