Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

z-Scores(standard deviation and mean) in PHP

I am trying to calculate Z-scores using PHP. Essentially, I am looking for the most efficient way to calculate the mean and standard deviation of a data set (PHP array). Any suggestions on how to do this in PHP?

I am trying to do this in the smallest number of steps.

like image 345
Spencer Avatar asked Mar 25 '11 15:03

Spencer


People also ask

How do you find z-score with mean and standard deviation?

The formula for calculating a z-score is is z = (x-μ)/σ, where x is the raw score, μ is the population mean, and σ is the population standard deviation. As the formula shows, the z-score is simply the raw score minus the population mean, divided by the population standard deviation.

How do you calculate standard deviation in PHP?

To calculate the standard deviation, we have to first calculate the variance. The variance can be calculated as the sum of squares of differences between all numbers and means. Finally to get the standard deviation we will use the formula, √(variance/no_of_elements).

Is z-score and SD same?

Key Takeaways. Standard deviation defines the line along which a particular data point lies. Z-score indicates how much a given value differs from the standard deviation. The Z-score, or standard score, is the number of standard deviations a given data point lies above or below mean.

How is z-score calculated?

If you know the mean you know the standard deviation. Take your data point, subtract the mean from the data point and then divide by your standard deviation. That gives you your Z-score.


2 Answers

to calculate the mean you can do:

$mean = array_sum($array)/count($array)

standard deviation is like so:

// Function to calculate square of value - mean
function sd_square($x, $mean) { return pow($x - $mean,2); }

// Function to calculate standard deviation (uses sd_square)    
function sd($array) {
    // square root of sum of squares devided by N-1
    return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)-1) );
}

right off this page

like image 184
Naftali Avatar answered Oct 12 '22 00:10

Naftali


How about using the built in statistics package like stats_standard_deviation and stats_harmonic_mean. I can't find a function for standard means, but if you know anything about statistics, I'm sure you can figure something out using the built-in functions.

like image 24
rockerest Avatar answered Oct 11 '22 22:10

rockerest