Wiki Home

Standard Deviation


Namespace: VFP
In probability and statistics, the standard deviation of a probability distribution, random variable, or population or multiset of values is defined as the square root of the variance.


To calculate the standard deviation of a population in VFP, use something like:
CALCULATE STD(fieldname) TO lnSTD

To calculate the standard deviation of a sample, you need a custom function. Here is one I wrote in a recent blog entry that also allows you to specify predicates as well. Any better solutions?

FUNCTION std_devs
  LPARAMETERS tcTableField, tcPredicates
  LOCAL nRet, nsavg , nscnt AS float

  SELECT(JUSTSTEM(tcTableField))
  IF !EMPTY(tcPredicates)
    CALCULATE AVG(&tcTableField) FOR &tcPredicates TO nsavg
    CALCULATE CNT(&tcTableField) FOR &tcPredicates TO nscnt
    SELECT SUM( (&tcTableField- nsavg) ^ 2 ) as ssum ;
        FROM JUSTSTEM(tcTableField)
        WHERE &tcPredicates
        INTO CURSOR crTmpSDEVS2
  ELSE
    CALCULATE AVG(&tcTableField) TO nsavg
    CALCULATE CNT(&tcTableField) TO nscnt
    SELECT SUM( (&tcTableField- nsavg) ^ 2 ) as ssum ;
        FROM JUSTSTEM(tcTableField)
        INTO CURSOR crTmpSDEVS2
  ENDIF

  nRet = SQRT(crTmpSDEVS2.ssum / (nscnt-1) )
  USE IN crTmpSDEVS2
  RETURN nRet
ENDFUNC


Reduced the number of passes at the table and added save/restore work area:

FUNCTION std_devs
  LPARAMETERS tcTableField, tcPredicates
  LOCAL nRet, nsavg , nscnt AS float, lnSelect
  * Save current work area
  lnSelect = SELECT()

  SELECT(JUSTSTEM(tcTableField))
  IF !EMPTY(tcPredicates)
    CALCULATE AVG(&tcTableField),CNT(&tcTableField) FOR &tcPredicates TO nsavg, nscnt
    CALCULATE SUM( (&tcTableField - nsavg) ^ 2 ) FOR &tcPredicates TO ssum
  ELSE
    CALCULATE AVG(&tcTableField),CNT(&tcTableField) TO nsavg, nscnt
    CALCULATE SUM( (&tcTableField - nsavg) ^ 2 ) TO ssum
  ENDIF

  nRet = SQRT(crTmpSDEVS2.ssum / (nscnt-1) )

  * Restore work area
  SELECT (lnSelect)
  RETURN nRet
ENDFUNC


Excellent improvement! -- Tod McKenna
Note: The line above "nRet = SQRT(crTmpSDEVS2.ssum / (nscnt-1) )" should read "nRet = SQRT(ssum / (nscnt-1) )" -- Tod McKenna

Contributors: Tod Mckenna, Jim BoothOffsite link to http://www.jamesbooth.com
Category Statistics
( Topic last updated: 2006.12.18 05:11:46 PM )