简体   繁体   中英

Java programming standard deviation error in code

My standard deviation is way off. When I enter: 2 4 4 4 5 5 7 9 n

I don't get 2. This is my code. I believe everything checks out so I don't understand why I keep getting 1.8284791953425266 instead of 2 :

import java.util.Scanner;

public class stocks {

  public static void main(String[] args) {

     Scanner in = new Scanner(System.in);
     double currentNum = 0;
     double numtotal = 0;
     int count = 0;
     double mean = 0;
     double square = 0, squaretotal = 0, sd = 0;

     System.out.println("Enter a series of double value numbers, ");
     System.out.println("Enter anything other than a number to quit: ");

     while (in.hasNextDouble()) 
     {

         currentNum = in.nextDouble();
         numtotal = numtotal + currentNum;

         count++;
         mean = (double) numtotal / count;
         square = Math.pow(currentNum - mean, 2.0);
         squaretotal = squaretotal + square; 
         sd = Math.pow(squaretotal/count, 1/2.0);
     }

     System.out.println("The mean is: " +mean);
     System.out.println("The standard deviation is: " +sd);

     }


 }

You need to work out the mean for all the numbers before you work out the standard deviation. Right now your mean is the average of all numbers up to the current number. Your problem is here

square = Math.pow(currentNum - mean, 2.0);

At this point the mean is the average of the numbers we've seen. This is because numtotal is the total of the numbers we've seen. To fix this you can take in all the numbers first into something like an array-list. Then work out the mean with all the numbers and after that you can work out the square differences and so the standard deviation.

count needs to be a double if you're going to divide by it.

mean = (double) numtotal / count;

-->

mean = (double) numtotal / (double) count;

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