A production machine produces bolts in large quantities. Periodically a small sample of the production is taken and each bolt in the sample measured for length and diameter.
Design a program to process such a sample, printing the mean length and mean diameter together with their standard deviation.
<? // this is how the standard deviation should be worked out, according to this wikipedia article // http://en.wikipedia.org/wiki/Standard_deviation function standard_deviation($array) { // 1. calculate the average $average = array_sum($array) / count($array); // 2. calculate diff from each to average for($n = 0; $n < count($array); $n++) $array[$n] = abs($array[$n] - $average); // 3. work out the square of each difference for($n = 0; $n < count($array); $n++) $array[$n] = pow($array[$n], 2); // 4. add up all the squares and find the average of that $total_squares = array_sum($array) / count($array); // 5. find the square root of that return sqrt($total_squares); } // first, generate a random sample // a small number is used because this will result in clearer outputs for ($n = 0; $n < mt_rand(3, 5); $n++) { // diameters are between 1.5 and 2.5 cm $diameters[] = 1.5 + (mt_rand(0, 10)/10); // lengths are between 7 and 13 cm $lengths[] = 7 + mt_rand(0, 6); } // show diameter output, for list, average and std dev echo 'Diameters<br/><ul>' . '<li>List: ' . implode(' cm, ', $diameters) . ' cm</li>' . '<li>Average: ' . round(array_sum($diameters) / count($diameters), 2) . ' cm</li>' . '<li>Standard deviation: ' . round(standard_deviation($diameters), 2) . ' cm</li>' . '</ul>'; // show lengths output, for list, average and std dev echo 'Lengths<br/><ul>' . '<li>List: ' . implode(' cm, ', $lengths) . ' cm</li>' . '<li>Average: ' . round(array_sum($lengths) / count($lengths), 2) . ' cm</li>' . '<li>Standard deviation: ' . round(standard_deviation($lengths), 2) . ' cm</li>' . '</ul>'; ?>Which produces:
DiametersLengths
- List: 2.5 cm, 2.1 cm, 1.9 cm
- Average: 2.17 cm
- Standard deviation: 0.25 cm
- List: 12 cm, 11 cm, 12 cm
- Average: 11.67 cm
- Standard deviation: 0.47 cm