0

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").

Community
  • 1
  • 1
Wistar
  • 3,770
  • 4
  • 45
  • 70

1 Answers1

1

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)) );
jon_darkstar
  • 16,398
  • 7
  • 29
  • 37
  • This is NOT to say you shouldn't figure out the scope problems going on, but this is the kind of use case where I like anonymous functions (you can also consider assigning to a variable right beforehand like `$f = function ($x, $mean) { return pow($x - $mean,2); }`, this line is pretty damn long already) – jon_darkstar Dec 09 '13 at 17:35
  • I guess that my class issue comes from the framework I'm using. I'll figure that out with the documentation. For now, the anonymous function will do the job. Thanks. – Wistar Dec 09 '13 at 17:53
  • 1
    Glad this works for you, but I really don't think the framework is the reason for your issue. I'd suggest you reorganize/refactor it all, and really look into the scope issues, when you have the time. They are likely to come up again. – jon_darkstar Dec 09 '13 at 17:58
  • @jon_darkstar, your formulas should end by `/ (count($array)-1) );` not `/ (count($array)) );`. Note the `-1`! (square root of sum of squares devided by N-1). See: https://www.php.net/manual/en/function.stats-standard-deviation.php#97369 – SAVAFA Dec 13 '20 at 23:20