Advertisement
luliu

Problem 7.11 Computing Deviation V2

Nov 20th, 2015
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. /*
  2.  * Lu Liu
  3.  * 11/20/2015
  4.  * CSCI-111-D01
  5.  * Problem 7.11 on page 278
  6.  * Computing Deviation V2
  7.  */
  8. package chapter07;
  9.  
  10. import java.util.Scanner;
  11.  
  12. public class ComputingDeviation {
  13.     public static void main(String[] args) {
  14.         Scanner input = new Scanner(System.in);
  15.         System.out.println("Enter your numbers: ");
  16.         double[] numbers = initArray(input);
  17.         displayArray(numbers);
  18.         System.out.println("The mean is " + mean(numbers));
  19.         System.out.println("The deviation is " + deviation(numbers));
  20.     }
  21.  
  22.     // First number in file indicates the number of numbers that follow
  23.     private static double[] initArray(Scanner input) {
  24.         int size = input.nextInt();
  25.         double x[] = new double[size];
  26.         for (int i = 0; i < x.length; i++)
  27.             x[i] = input.nextDouble();
  28.         return x;
  29.     }
  30.  
  31.     // calculate mean
  32.     public static double mean(double[] x) {
  33.         double sum = 0;
  34.         for (int i = 0; i < x.length; i++)
  35.             sum += x[i];
  36.         return sum / x.length;
  37.     }
  38.  
  39.     // calculate deviation
  40.     public static double deviation(double[] x) {
  41.         double mean = mean(x);
  42.         double sum = 0;
  43.         for (int i = 0; i < x.length; i++)
  44.             sum += (x[i] - mean) * (x[i] - mean);
  45.         return Math.sqrt(sum / (x.length - 1));
  46.     }
  47.  
  48.     // print array
  49.     public static void displayArray(double[] x) {
  50.         for (int i = 0; i < x.length; i++) {
  51.             if ((i + 1) % 20 == 0)
  52.                 System.out.println(x[i]);
  53.             else
  54.                 System.out.print(x[i] + " ");
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement