Jump to content

Array: Calculate square root X - Average


MasterACE14

Recommended Posts

Hello,

 

I'm trying to calculate the square root of X values in an array minus the average of the array, but the first half of the values are negative, so I'm using the abs(); function to change them to positives first, but I'm still getting "NAN" as the result for the negative values that 'should' be positive.

        $x = array(7,3,4,6,4,2,7);
        $sqrt = true;
        $x = sort($x);
        $mean = 4.71; // average
        $XminA = array();
        foreach($x as $val) {
            ($sqrt == true) ? $XminA[] = round(sqrt(abs($val) - $mean),2) : $XminA[] = round($val - $mean,2);
        }
        echo "<pre>";
        print_r($XminA);
        echo "</pre>";

 

and my result is...

[XminA] => Array

        (

            [0] => NAN

            [1] => NAN

            [2] => NAN

            [3] => NAN

            [4] => 1.14

            [5] => 1.51

            [6] => 1.51

        )

 

Not sure what I'm doing wrong, any help is appreciated. Thank you!

 

Kind Regards,

Ace

 

EDIT: stupid mistake, need it to the power of 2 not square root. Using the wrong function sorry:

 ($sqrt == true) ? $XminA[] = round(pow((abs($val) - $mean),2) : $XminA[] = round($val - $mean,2); // pow() not sqrt()

[XminA] => Array

        (

            [0] => 7.34

            [1] => 2.92

            [2] => 0.5

            [3] => 0.5

            [4] => 1.66

            [5] => 5.24

            [6] => 5.24

        )

Link to comment
https://forums.phpfreaks.com/topic/238067-array-calculate-square-root-x-average/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.