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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.