' ******************************************************************
' Statistical distribution
' ******************************************************************

TYPE StatClass    ' Statistical class
  Inf AS DOUBLE   ' Lower bound
  Sup AS DOUBLE   ' Upper bound
  N   AS INTEGER  ' Number of values
  F   AS DOUBLE   ' Frequency
  D   AS DOUBLE   ' Density
END TYPE

FUNCTION NumCls(X AS DOUBLE, A AS DOUBLE, H AS DOUBLE) AS INTEGER
' Returns the index of the class containing X
' A is the lower bound of the first class
' H is the class width

  DIM AS DOUBLE  Y
  DIM AS INTEGER I

  Y = (X - A) / H
  I = INT(Y)
  IF Y <> I THEN I = I + 1
  NumCls = I
END FUNCTION

SUB Distrib(      X()  AS DOUBLE,  _
                  A    AS DOUBLE,  _
                  H    AS DOUBLE,  _
            BYREF Ntot AS INTEGER, _
                  C()  AS StatClass)
' ------------------------------------------------------------------
' Distributes the values of array X() into N classes with equal 
' width H, according to the following scheme:
'
'             C(1)    C(2)                    C(N)
'          ]-------]-------].......]-------]-------]
'          A                                       A+N*H
'
' Ntot is the total number of values in the classes
' ------------------------------------------------------------------

  DIM AS INTEGER I, K, Lb, Ub

  Lb = LBOUND(C)
  Ub = UBOUND(C)
  
  FOR K = Lb TO Ub
    C(K).N = 0
  NEXT K

  FOR I = LBOUND(X) TO UBOUND(X)
    K = NumCls(X(I), A, H)
    IF K >= Lb AND K <= Ub THEN C(K).N = C(K).N + 1
  NEXT I

  Ntot = 0
  FOR K = Lb TO Ub
    Ntot = Ntot + C(K).N
  NEXT K
  
  FOR K = Lb TO Ub
    WITH C(K)
      .Inf = A + (K - 1) * H
      .Sup = .Inf + H
      .F = .N / Ntot
      .D = .F / H
    END WITH
  NEXT K
END SUB
