简体   繁体   中英

Standard Deviation java, proper equation

This is all my code. I am having problems with the standard deviation formula. I run the program with these values:

Number of items: 5

Items: 16 25 81 80 24

I'm supposed to get this output:

Average: 45.20

Std Dev: 32.41

Less than Avg: 3

Array is not in sorted order

Instead, I get this output:

Array is not in sorted order

Average: 45.20

Std Dev: 55.60

Less than Avg: 3

import java.text.DecimalFormat;
import java.util.Scanner;
public class array {

public static void main(String[] args) {
Scanner input = new Scanner(System.in); 
DecimalFormat df = new DecimalFormat ("#.00");
System.out.println("How many values do you want?");
int num = input.nextInt(); 
if (num< 1 || num > 100)
{
    System.out.println("Error");
    System.exit(0);
}
int[] array= valueArray(input, num);
double o= average(num,  array);
double standdev = getStdDev(array, num); 
int lessThanAvg = lessAvg ( array, num, o );
boolean sorted=isArraySorted(array, num);
System.out.println("Average: " + df.format(o));
System.out.println("Std Dev: " + df.format(standdev));
System.out.println("Less than Avg: " + lessThanAvg);
}

public static int[] valueArray (Scanner input, int num )
{
    int[] values = new int[100]; 
    System.out.println("What numbers do you want to put in?");
    for (int j = 0; j < num; j++)
    {
        values[j]=input.nextInt();

    }
    return values;
}
public static double average ( int num ,int[] values)
{
    double avg=0.0;
    for (int i = 0; i < num; i++)
    {
        avg = avg+values[i];
    }

    return avg/num;
}

public static double getStdDev (int [] values, int num)
{
    double avg = 0.0;
    double sum = 0 ;
    for (int i = 0; i < num - 1; i++)
    {

        sum = Math.sqrt ((Math.pow((values[i]-avg),2) + Math.pow((values[num-1]),2)) / num-1);


    }
    return sum;

}
public static int lessAvg ( int [] values, int num, double avg )
{
    int counter = 0;
    for (int i = 0; i < num; i++ )
    {
        if (values[i] < avg)
        {
            counter = counter + 1;
        }
    }
    return counter;
}
public static boolean isArraySorted (int [] values, int num)
{
    for (int i = 0; i < num - 2; i++)
    {
        if (values[i]>values[i+1])
        {
            System.out.println("Array is not in sorted order");
            return false;

        }
    }

     System.out.println("Array is in sorted order"); 
    return true;
}
}

to get the standard deviation

  1. find out the mean.

  2. Then for each number of your array subtract the Mean and square the result.

  3. Then work out the mean of those squared differences

  4. find the square root of that.

For reference you can look at this Post

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