简体   繁体   中英

Calculating standard deviation in java

Do I calculate my standard deviation in the loop. I know the formula for calculate the standard deviation, I just want to know how to take user inputs for the calculation. I'm new to programming so please explain everything. I also don't mind my sorry attempt at trying to write out Standard deviation formula it wasn't meant to work just to understand SD more.

import java.util.Scanner; 

public class readFromKeyboard { 
  public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    String inStr = input.next(); 
    int n;
    int i;
    int count = 0; 
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE; 
    double average=0;
    int sum;
    double deviation = 0;

    while (!inStr.equals("EOL")) { 
      count++; 
      n = Integer.parseInt(inStr); 
      min = Math.min(min, n);
      max = Math.max(max, n);
      System.out.printf("%d ", n); 
      inStr = input.next(); 
      average += n;
      // really bad attempt here
      deviation = math.pow(n / average,2) ++ / mean sqrt(); 
    } 
    average = average/count;
    System.out.println("\n The average of these numbers is " + average);
    System.out.printf("The list has %d numbers\n", count); 
    System.out.printf("The minimum of the list is %d\n", min);
    System.out.printf("The maximum of the list is %d\n", max);

    input.close(); 
  } 
}

A few issues with your code first:

Your use of average is very confusing, since you are first using it as an accumulator and only then dividing it by the number of elements. Far better style would be to use a separate accumulator variable to calculate the sum, and then calculate average outside the for loop.

That being said, once average is calculated, you can then loop through your values again, and keep an accumulator variable that for each number increases by the square of the difference between it and the mean, along the lines of:

varianceSum += Math.pow(num - average, 2);

Once all numbers are summed up, you can divide varianceSum by count to get the variance (perhaps with a check to avoid division by 0), and use Math.sqrt() to find the standard deviation.

As for getting input from the user, you will need to call input.nextInt() repeatedly for every number. You can either have the user enter the number of inputs at the beginning, and then loop through them in a for loop, or you can read until you reach the end of the input using Scanner's hasNext() method.

You should call input.next(); inside the loop to get user input repeatedly.

For the record, you can use in.nextInt() instead of input.next(); , as you are dealing with integers here. Your calculation of deviation is not clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM