The problem Programming exercise computes the standard deviation of numbers. This exercise uses a different but equivalent formula to compute the standard deviation of n numbers. To compute the standard deviation with this formula, you have to store the individual numbers using an array, so that they can be used after the mean is obtained . Your program should contain the following methods:
public static double deviation(double[] x)
public static double mean(double[] x)
Breaking it down static final int USER_INPUT_SIZE = 10 ;
public static void main ( String [] args ) {
Scanner input = new Scanner ( System . in );
double [] numbers = new double [ USER_INPUT_SIZE ];
System . out . print ( "Enter " + USER_INPUT_SIZE + " numbers: " );
for ( int i = 0 ; i < numbers . length ; i ++) {
numbers [ i ] = input . nextDouble ();
}
input . close ();
System . out . println ( "The mean is: " + mean ( numbers ). getAsDouble ());
System . out . println ( "The standard deviation is: " + deviation ( numbers ));
}
public static double deviation ( double [] x ) {
double mean = mean ( x ). getAsDouble ();
double deviation = 0 ;
for ( int i = 0 ; i < x . length ; i ++) {
deviation += Math . pow ( x [ i ] - mean , 2 );
}
return Math . sqrt ( deviation / ( x . length - 1 ));
}
public static OptionalDouble mean ( double [] x ) {
return Arrays . stream ( x ). average ();
}
Output Enter 10 numbers: 2
886
44
33
66
88
99
55
22
22
The mean is: 131.7
The standard deviation is: 266.7645861887301
Compute deviation posted by Justin Musgrove on 24 April 2016
Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch7
Share on: Facebook Google+