ross.c
ross.c

Reputation: 143

computing mean and standard deviation

creating a program that enables the user to enter an integer N, then reads N double values, and prints their mean (average value) and sample standard deviation (square root of the sum of the squares of their differences from the average, divided by N - 1). So far I have this code

import java.util.Scanner;

public class AVGDevi

{

public static void main(String[] args) 
{
    Scanner input = new Scanner(System.in);



    double x;

    double sum = 0;

    double average = 0;

    double dev = 0;

    double var = 0;

    double sqrx = 0;

    int n = 0;

    do 
    { 
        System.out.println("Enter an integer:");
        x = input.nextInt(); 
        if (x == -1)
        {
            break;
        }

        sum += x;
        n++;
        average = sum / n;      
        sqrx += Math.pow(x-average,2);
        var = sqrx / (n-1);
        dev = Math.sqrt(var);


    } while (x<= 0);

    System.out.println("Average: " + average);
    System.out.println("Deviation: " + dev);
  }

}

test case:

5
1
2
3
4
5

Currently getting this output

Enter an integer:
Average: 5.0
Deviation: NaN

Output should be

Enter an integer: Enter a number: Enter a number: Enter a number: Enter a number: Enter a number: Average value is: 3.0
The standard deviation is: 1.58

I'm not 100% sure what I'm doing wrong any help would be great :D !

Upvotes: 1

Views: 477

Answers (2)

Kaushal28
Kaushal28

Reputation: 5557

You can use only while loop instead of do-while loop, as following:

public static void main(String[] args) 
{
Scanner input = new Scanner(System.in);




double y=-1;

double sum = 0;

double average = 0;

double dev = 0;

double var = 0;

double sqrx = 0;

int n = 0;


    System.out.println("Enter an integer:");
    y = input.nextInt();
    double z=y;
    int i=0;
    double x[] = new double[(int)z];
    while(y-->0){

   x[i] = input.nextDouble();

    sum += x[i];
   i++;         
    n++;
    average = sum / n;      


    }
    i=0;
    while(z-->0){
        sqrx += Math.pow(x[i]-average,2);
        i++;
    }
 var = sqrx / (n-1);
    dev = Math.sqrt(var);

System.out.println("Average: " + average);
System.out.println("Deviation: " + dev);
  }

Upvotes: 1

naffarn
naffarn

Reputation: 562

You are using x <= 0 in the do-while guard, so if you enter a positive number, it will exit after the first iteration. Also, when you enter the first number, you will have var = sqrx / (n-1), but for n=1, you are dividing by 0. As Hovercraft Full Of Eels suggested, I'd add the numbers into a vector or ArrayList and do the calculation after you receive all input.

Upvotes: 1

Related Questions