Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Lu Liu
- * 11/20/2015
- * CSCI-111-D01
- * Problem 7.11 on page 278
- * Computing Deviation V2
- */
- package chapter07;
- import java.util.Scanner;
- public class ComputingDeviation {
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- System.out.println("Enter your numbers: ");
- double[] numbers = initArray(input);
- displayArray(numbers);
- System.out.println("The mean is " + mean(numbers));
- System.out.println("The deviation is " + deviation(numbers));
- }
- // First number in file indicates the number of numbers that follow
- private static double[] initArray(Scanner input) {
- int size = input.nextInt();
- double x[] = new double[size];
- for (int i = 0; i < x.length; i++)
- x[i] = input.nextDouble();
- return x;
- }
- // calculate mean
- public static double mean(double[] x) {
- double sum = 0;
- for (int i = 0; i < x.length; i++)
- sum += x[i];
- return sum / x.length;
- }
- // calculate deviation
- public static double deviation(double[] x) {
- double mean = mean(x);
- double sum = 0;
- for (int i = 0; i < x.length; i++)
- sum += (x[i] - mean) * (x[i] - mean);
- return Math.sqrt(sum / (x.length - 1));
- }
- // print array
- public static void displayArray(double[] x) {
- for (int i = 0; i < x.length; i++) {
- if ((i + 1) % 20 == 0)
- System.out.println(x[i]);
- else
- System.out.print(x[i] + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement