! Program Example from "Essential Fortran 90 & 95" by Loren P. Meissner
! Copyright 1996. Copying for sale requires permission from the author.
! Otherwise, distribution is permitted if these three lines are included.

! Example 4.24. Statistics by updating method.
  module E24M
    implicit none
    public :: Tally, Report
    integer, save, public :: How_Many = 0
    real, public :: X, Y,X_Mean, Y_Mean, X_Dev, Y_Dev, Covar, Correlation
    real, save, private :: X_Sum = 0.0, Y_Sum = 0.0, &
      XX_Res = 0.0, YY_Res = 0.0, XY_Res = 0.0
  contains
    subroutine Tally( )
      How_Many = How_Many + 1
      X_Sum = X_Sum + X
      Y_Sum = Y_Sum + Y
      if (How_Many > 1.0) then
        XX_Res = XX_Res + (real( How_Many ) * X - X_Sum) ** 2 &
          / (real( How_Many ) * (real( How_Many ) - 1.0))
        YY_Res = YY_Res + (real( How_Many ) * Y - Y_Sum) ** 2 &
          / (real( How_Many ) * (real( How_Many ) - 1.0))
        XY_Res = XY_Res &
          + (real( How_Many ) * X - X_Sum) * (real( How_Many ) * Y - Y_Sum) &
          / (real( How_Many ) * (real( How_Many ) - 1.0))
      end if
      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_Res / real( How_Many ) )
          Y_Dev = sqrt( YY_Res / real( How_Many ) )
          Covar = XY_Res / real( How_Many )
          Correlation = Covar / (X_Dev * Y_Dev)
        end if
      end if
      return
    end subroutine Report
  end module E24M

