Tech Tip: Utility Method To Return the Statistical Mean of an Array
PRODUCT: 4D | VERSION: 14.x | PLATFORM: Mac & Win
Published On: May 11, 2016
Below is a utility method to obtain the statistical mean of an array. A statistical mean is the distinct value in a set that occurs the most amount of times, if there are two values that occur the most of the same times then the method will return the first of the two.
// Util_GetMean // // Desription: // Gets the Statistical Mean of an Array // // Parameters: // $1: Pointer to an Array of Numbers // $2: Pointer to Resulting Value // ---------------------------------------------------- C_POINTER($1) C_POINTER($array_ptr;$value_ptr) C_POINTER($2) C_LONGINT($total_l) C_LONGINT($count_l) C_LONGINT($arrType) If (Count parameters=2) $arrType:=Type($1->{1}) Case of : ($arrType=Is text)    ARRAY TEXT($temp_at;0) C_TEXT($value_t) $array_ptr:=->$temp_at $value_ptr:=->$value_t : ($arrType=Is longint) ARRAY LONGINT($temp_al;0) C_LONGINT($value_l) $array_ptr:=->$temp_al $value_ptr:=->$value_l : ($arrType=Is Boolean) ARRAY BOOLEAN($temp_ab;0) C_BOOLEAN($value_b) $array_ptr:=->$temp_ab $value_ptr:=->$value_b : ($arrType=Is real) ARRAY REAL($temp_ar;0) C_REAL($value_r) $array_ptr:=->$temp_ar $value_ptr:=->$value_r End case COPY ARRAY($1->;$array_ptr->) SORT ARRAY($array_ptr->) $total_l:=1 $count_l:=0 While ($total_l<Size of array($array_ptr->)) If ($count_l<Count in array($array_ptr->;$array_ptr->{$total_l})) $count_l:=Count in array($array_ptr->;$array_ptr->{$total_l}) $value_ptr->:=$array_ptr->{$total_l} End if $total_l:=$total_l+Count in array($array_ptr->;$array_ptr->{$total_l}) End while $2->:=$value_ptr-> End if |
Example of using the method:
ARRAY LONGINT($arr;0) C_LONGINT($var_l) APPEND TO ARRAY($arr;1) APPEND TO ARRAY($arr;1) APPEND TO ARRAY($arr;1) APPEND TO ARRAY($arr;1) APPEND TO ARRAY($arr;1) APPEND TO ARRAY($arr;2) APPEND TO ARRAY($arr;2) APPEND TO ARRAY($arr;3) APPEND TO ARRAY($arr;3) APPEND TO ARRAY($arr;3) APPEND TO ARRAY($arr;3) APPEND TO ARRAY($arr;3) APPEND TO ARRAY($arr;3) APPEND TO ARRAY($arr;3) APPEND TO ARRAY($arr;2) APPEND TO ARRAY($arr;2) APPEND TO ARRAY($arr;2) Util_GetMean(->$arr;->$var_l) |
Result:
$var_l=3