Pages

Saturday, 20 August 2016

Chapter 7 Exercise 11, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*7.11 (Statistics: compute deviation) Programming Exercise 5.45 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:

 /** Compute the deviation of double values */
public static double deviation(double[] x)
 /** Compute the mean of an array of double values */
public static double mean(double[] x)

Write a test program that prompts the user to enter ten numbers and displays the mean and standard deviation, as shown in the following sample run:

Enter ten numbers: 1.9 2.5 3.7 2 1 6 3 4 5 2
The mean is 3.11
The standard deviation is 1.55738 



import java.util.Scanner;
 
 
public class ProgrammingEx7_11 {
 
 public static void main(String[] args) {
  System.out.print("Enter ten numbers:");
  Scanner input = new Scanner(System.in);
  double[] numbers = new double[10];
 
  for (int i = 0; i < numbers.length; i++) {
   numbers[i] = input.nextDouble();
  }
 
  System.out.println("The mean is " + mean(numbers));
  System.out.println("The standard deviation is " + deviation(numbers));
 
 }
 
 /** Compute the deviation of double values */
 public static double deviation(double[] x) {
  double mean = mean(x);
  double sumSq = 0;
  for (int i = 0; i < x.length; i++) {
   sumSq += Math.pow((x[i] - mean), 2);
  }
 
  return Math.sqrt(sumSq / (x.length - 1));
 
 }
 
 /** Compute the mean of an array of double values */
 public static double mean(double[] x) {
  double sum = 0;
  for (int i = 0; i < x.length; i++) {
   sum += x[i];
  }
 
  return sum / x.length;
 
 }
 
}

No comments:

Post a Comment