' ******************************************************************
' Mean and standard deviations
' ******************************************************************

FUNCTION Mean(X() AS DOUBLE) AS DOUBLE
' Mean of sample X

  DIM AS DOUBLE  SX
  DIM AS INTEGER I, Lb, Ub

  Lb = LBOUND(X)
  Ub = UBOUND(X)

  SX = 0
  FOR I = Lb TO Ub
    SX = SX + X(I)
  NEXT I

  Mean = SX / (Ub - Lb + 1)
END FUNCTION

FUNCTION StDev(X() AS DOUBLE, M AS DOUBLE) AS DOUBLE
' Standard deviation estimated from sample X

  DIM AS DOUBLE  D, SD, SD2, V
  DIM AS INTEGER Lb, Ub, I, N

  Lb = LBOUND(X)
  Ub = UBOUND(X)
  N = Ub - Lb + 1

  SD = 0   ' Sum of deviations (used to reduce roundoff error)
  SD2 = 0  ' Sum of squared deviations
  
  FOR I = Lb TO Ub
    D = X(I) - M
    SD = SD + D
    SD2 = SD2 + D * D
  NEXT I

  V = (SD2 - SD * SD / N) / (N - 1)  ' Variance
  StDev = SQR(V)
END FUNCTION

FUNCTION StDevP(X() AS DOUBLE, M AS DOUBLE) AS DOUBLE
' Standard deviation of population

  DIM AS DOUBLE  D, SD, SD2, V
  DIM AS INTEGER Lb, Ub, I, N

  Lb = LBOUND(X)
  Ub = UBOUND(X)
  N = Ub - Lb + 1

  SD = 0   ' Sum of deviations (used to reduce roundoff error)
  SD2 = 0  ' Sum of squared deviations
  
  FOR I = Lb TO Ub
    D = X(I) - M
    SD = SD + D
    SD2 = SD2 + D * D
  NEXT I

  V = (SD2 - SD * SD / N) / N  ' Variance
  StDevP = SQR(V)
END FUNCTION
