# Robson » Little Red Book » Mean and standard deviation

## Chapter 3 - Question 12

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.

### Solution 1

`<?`
` `
`    // 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('&nbsp;cm, ', \$diameters) . '&nbsp;cm</li>' .`
`         '<li>Average: ' . round(array_sum(\$diameters) / count(\$diameters), 2) . '&nbsp;cm</li>' .`
`         '<li>Standard deviation: ' . round(standard_deviation(\$diameters), 2) . '&nbsp;cm</li>' .`
`         '</ul>';`
`    // show lengths output, for list, average and std dev`
`    echo 'Lengths<br/><ul>' . `
`         '<li>List: ' . implode('&nbsp;cm, ', \$lengths) . '&nbsp;cm</li>' .`
`         '<li>Average: ' . round(array_sum(\$lengths) / count(\$lengths), 2) . '&nbsp;cm</li>' .`
`         '<li>Standard deviation: ' . round(standard_deviation(\$lengths), 2) . '&nbsp;cm</li>' .`
`         '</ul>';`
`    `
` `
`?>`

Which produces:

Diameters
• List: 2.1 cm, 2.3 cm, 1.7 cm
• Average: 2.03 cm
• Standard deviation: 0.25 cm
Lengths
• List: 10 cm, 13 cm, 10 cm
• Average: 11 cm
• Standard deviation: 1.41 cm

## Log

• September 10, 2006 - Added solution 1.
© 2004-19 robson | cc unless stated