88. PHP Program to find Mean, Variance and Standard Deviation of given N numbers.
How does this program work?
- This program is used to find mean, variance and standard deviation of given numbers using PHP.
Here is the code
<html>
<head>
<title>PHP Program To find mean, variance and standard deviation of given numbers</title>
</head>
<body>
<?php
function findMean(&$a, $n)
{
$sum = 0;
for ($i = 0; $i < $n; $i++)
$sum += $a[$i];
return (double)$sum / (double)$n;
}
function variance( $a, $n)
{
// Compute mean (average of elements)
$sum = 0;
for ( $i = 0; $i < $n; $i++)
$sum += $a[$i ];
$mean = $sum / $n;
// Compute sum squared differences with mean.
$sqDiff = 0;
for ( $i = 0; $i < $n; $i++)
$sqDiff += ($a[$i] - $mean) * ($a[$i] - $mean);
return $sqDiff / $n;
}
function standardDeviation($a, $n)
{
return sqrt(variance($a, $n));
}
$a = array(1, 2, 3, 4, 5);
$n = sizeof($a);
$precision = 4;
echo "Given array of elements : ";
foreach( $a as $b)
{
echo $b. " ";
}
echo " Mean = " . findMean($a, $n);
echo "Variance = ".variance($a, $n);
echo "Standard Deviation = ".number_format(standardDeviation($a, $n), $precision);
return 0;
?>
</body>
</html>