Cham Cham - 3 months ago 8
Java Question

Standard Deviation

Hi I have created a code to calculate the standard deviation of a set of numbers, here my code below:

public class standardDev {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
double sum = 0.0;
for(int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
Arrays.sort(arr);
double median = n % 2 != 0 ? arr[n/2] : (arr[n/2] + arr[(n/2)-1])/2;
for(int i = 0; i < n; i++) {
sum += Math.pow(arr[i] - median,2);
}
System.out.printf("%.1f", Math.sqrt(sum/n));
}
}


However when the input is this:


10

64630 11735 14216 99233 14470 4978 73429 38120 51135 67060


I get a different result from the expected answer.
My output:
30475.6

Expected output:
30466.9


But if I tried the input below I get the correct answer:


5

10 40 30 50 20


My output:
14.1


Expected output:
14.1

Answer

Rewrote your code to actually calculate the standard deviation, which is based on the mean:

import java.util.*;
import java.lang.*;
import java.io.*;

class standardDev
{
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] arr = new int[n];
        double sum = 0.0;
        double mean = 0;
        for(int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
            mean += arr[i];
        }
        mean /= n;
        for(int i = 0; i < n; i++) {
            sum += Math.pow(arr[i] - mean,2);
        }
        System.out.printf("%.1f", Math.sqrt(sum/n));
   }
}

Example: http://ideone.com/qY1wkw