Example 4.4 Computing Mean and Standard
Deviations
In this example, you will write a
program that generates 10 random numbers and computes the mean and standard
deviations of these numbers using the following formula:
A sample run of the following program is shown in Figure 4.8.
// ComputeMeanDeviation.java: Demonstrate using the math methods
public class ComputeMeanDeviation
{
/**Main
method*/
public
static void main(String[] args)
{
final int count = 10; // Total numbers
int number = 0; // Store a random number
double sum = 0; // Store the sum of the
numbers
double squareSum = 0; // Store the sum of
the squares
// Create numbers, find its sum, and its square sum
for (int i=0; i<count; i++)
{
// Generate a new random number
number = (int)Math.round(Math.random()*1000);
System.out.println(number);
// Add the number to sum
sum += number;
// Add the square of the number to squareSum
squareSum += Math.pow(number, 2); // Same
as number*number;
}
// Find mean
double mean = sum/count;
// Find standard deviation
double deviation = Math.sqrt((squareSum -
sum*sum/count)/(count - 1));
// Display result
System.out.println("The mean is
" + mean);
System.out.println("The standard
deviation is " + deviation);
}
}
Figure 4.8
The program finds the mean and
standard deviations of 10 random integers.
Example Review
The program demonstrates the use of the
math methods random, round, pow, and sqrt. The random
method generates a double value that is greater than or equal to 0 and
less than 1.0. After multiplying the generated number by 1000, the random number
is greater than or equal to 0 and less than 1000.0. The round method
converts the double number into a long value, which is cast into an int
variable number.
Invoking pow(number, 2) returns
the square of number. The sqrt method is used to get the square
root of a double value.
The formula for computing standard
deviation used in the example is equivalent to the following formula:
To use this formula, you have to store the individual numbers using an array so
that they can be used after the mean is obtained.