PHP Standard Deviation. Array_map function not found inside class function

786 views Asked by At

I'm trying to perform a Standard Deviation with PHP.

I used this function I founded there because the stats_standard_deviation doesn't seem to be reliable

    <?php 
    class TestController extends \BaseController {

         function MyFunction() {
             $array = array('1','2','3','4');
             function sd_square($x, $mean) { return pow($x - $mean,2); } 

             function sd($array) { 
                      return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)) ); 
             } 
    } return sd($array)
} ?> 

The problem is that it returns me array_map() expects parameter 1 to be a valid callback, function 'sd_square' not found or invalid function name when I try to use it.

Looking at some post here I tried to change "sd_square" for "self::sd_square" or array($this, "sq_square").

1

There are 1 answers

4
jon_darkstar On BEST ANSWER

This kind of sidesteps the issue (and you should address it), but sq_square is small enough you may want to consider simply inlining

Change:

return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)) );

To:

return sqrt(array_sum(array_map(function ($x, $mean) { return pow($x - $mean,2); }, $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)) );

Or:

$sd_square = function ($x, $mean) { return pow($x - $mean,2); };
return sqrt(array_sum(array_map($sd_square, $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)) );