phparraysfilteringstandard-deviationtrilateration

Filter Standard Deviation using PHP


I want to filter how many level I will add with my standard deviation result. These are steps that I need to do:

  1. Calculate the standard deviation based on array value. (solve)

  2. Find the average of the array value and add with the standard deviation result. eg : average = -49.7 s.d = 3.37

So, i need to keep adding the value until I get a new list of number. eg: -49.7, -46.33, -42.96, -39.59

After that, I need to filter only print the array value from -49.7 to -39.59 only.

Can anybody help me on this?


Solution

  • Here is the script from what I could understand the question.

    If you need any explanation or the code is not what you want then let me know in the comment section.

    <?php 
    
    $array = [2,4,6,8,10];
    
    $resultList = "";
    $resultList_rounded = "";
    
    function standardDeviation($array){
    
        //sum of all values
        $sum = array_sum($array);
    
        //sum of (square of values)
        $sum_of_square = array_sum(array_map(function($value){return $value*$value;},$array));
    
        //X Bar
        $xBar = average($array);
    
        //variance
        $variance = ($sum_of_square/count($array))-pow($xBar,2);
    
        //standard deviation
        return sqrt($variance);
    }
    
    function average($array){
        return (array_sum($array)/count($array));
    }
    
    function newList($array,$rounded=false,$round_digits = 4){
        $newarray = [];
        $sd = standardDeviation($array);
        $avg = average($array);
    
        for($i=1;$i<=count($array);$i++){
            if(empty($newarray)){
                array_push($newarray,$avg);
                continue;
            }
            if(!$rounded){
            array_push($newarray,$array[$i-1]+$sd);
            }else{
            array_push($newarray,number_format((float) ($array[$i-1]+$sd), $round_digits, '.', ''));
            }
        }
        return implode(',',$newarray);
    }
    
    function getRange($array){
        return $array[0]." to ".$array[count($array)-1];
    }
    
    //get new list
    $resultList = newList($array,true,0); 
    /*In the line above this, replace false with true if you want the rounded version and false if you want non rounded version. 4 means the number of digits to round.
    examples:
    $resultList = newList($array,true,4); will print 6,6.8284,8.8284,10.8284,12.8284
    $resultList = newList($array,false,4);  will print 6,6.8284271247462,8.8284271247462,10.828427124746,12.828427124746
    $resultList = newList($array,true,0); will print 6,7,9,11,13
    $resultList = newList($array,true,1); will print 6,6.8,8.8,10.8,12.8
    */
    
    //print the new result list
    echo $resultList;