PHP program to find the Standard Deviation of an array
Given an array of elements. We need to find the
Standard Deviationof the elements of the array in PHP. Examples:
Input : array(2, 3, 5, 6, 7)
Output : 1.5620499351813
Input : array(1, 2, 3, 4, 5)
Output : 1
The following problem can be solved using the
PHPinbuilt functions. The inbuilt functions used to solve the above problem are as such:
- array_sum(): The function returns the sum of all the elements of an array.
- count(): This function gives the number of elements currently present in the given array.
- sqrt(): The function returns the square root of the given number.
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). Below is the implementation in PHP to calculate the standard deviation:
<?php
// function to calculate the standard deviation
// of array elements
function Stand_Deviation($arr)
{
$num_of_elements = count($arr);
$variance = 0.0;
// calculating mean using array_sum() method
$average = array_sum($arr)/$num_of_elements;
foreach($arr as $i)
{
// sum of squares of differences between
// all numbers and means.
$variance += pow(($i - $average), 2);
}
return (float)sqrt($variance/$num_of_elements);
}
// Input array
$arr = array(2, 3, 5, 6, 7);
print_r(Stand_Deviation($arr));
?>
Output:
1.8547236990991
Using MathPHP Library
To find the standard deviation of an array in PHP using the MathPHP library, include the library, then call the StandardDeviation::population() method with the array as an argument. This returns the standard deviation of the population.
Example
<?php
function Stand_Deviation($arr)
{
$num_of_elements = count($arr);
$variance = 0.0;
// Calculate mean using array_sum() method
$average = array_sum($arr) / $num_of_elements;
foreach($arr as $i)
{
// Sum of squares of differences between all numbers and means.
$variance += pow(($i - $average), 2);
}
return (float)sqrt($variance / $num_of_elements);
}
// Input array
$arr = [2, 3, 5, 6, 7];
echo Stand_Deviation($arr);
?>
Output:
1.8547236990991