3)
To write a procedure to perform this calculation, one might write a program to do the following:
Set SUM and SUMSQUARES equal to 0.0
Set n = size of the array of scores
Start with the first score, and continue until all the scores have been processed
Set SUM = SUM + score
Set SUMSQUARES = SUMSQUARES + score2
End of loop
Set MEAN = SUM/n
Return the SquareRoot of (SUMSQUARES ??’ n * MEAN2) / (n ??’ 1)
This is the recipe, the procedure, the pseudocode, for calculating the standard deviation of an array of
numbers. Here is a Java class called Sd that implements such a procedure in a routine called stdDev:
import java.lang.Math;
class Sd {
public static void main( String args[] ){
float[] numbers = { 3, 5, 7, 9 };
System.out.println( "Std. dev. = " + stdDev( numbers) );
}
public static float stdDev( float scores[] ) {
float sum = 0;
float sumSquares = 0;
int n = scores.length;
for( int i = 0; i < n; i++ ) {
sum = sum + scores[i];
sumSquares = sumSquares + scores[i]*scores[i];
}
float mean = sum / n;
float variance = (sumSquares - n*mean*mean) / (n - 1);
return (float)Math.sqrt( variance );
}
}
s x nx n i
i
n
= ??’ ??’
= ??‘
( )/( ) 2
1
2 1
s x x n i
i
n
= ??’ ??’
= ??‘
( )/( ) 2
1
1
x
s m = ??’
= ??‘
( )/ x n i
i
n
2
1
50 SOFTWARE [CHAP.
Pages:
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145