简体   繁体   English

标准偏差

[英]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 10

64630 11735 14216 99233 14470 4978 73429 38120 51135 67060 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 我的输出: 30475.6预期输出: 30466.9

But if I tried the input below I get the correct answer: 但是,如果我尝试下面的输入,则会得到正确的答案:

5 5

10 40 30 50 20 10 40 30 50 20

My output: 14.1 我的输出: 14.1

Expected output: 14.1 预期产量: 14.1

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 示例: http//ideone.com/qY1wkw

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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