Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Standard Deviation

Posted on 2014-02-11
7
1,327 Views
Last Modified: 2014-02-11
I am trying to solve an exercise problem from the Practice-It! website.

I am not a student but I have purchased the book(Building Java Programs) from Amazon. I am trying to teach myself how to code. It is not my intention to violate any EE terms of restriction.

Problem link
Exercise 7.6: stdev

 Write a method called stdev that returns the standard deviation of an array of integers. Standard deviation is computed by taking the square root of the sum of the squares of the differences between each element and the mean, divided by one less than the number of elements. (It's just that simple!)

More concisely and mathematically, the standard deviation of an array a is written as follows:
standard deviation

For example, if the array passed contains the values {1, -2, 4, -4, 9, -6, 16, -8, 25, -10}, your method should return approximately 11.237. You may assume that the array passed is non-null and contains at least two values, because the standard deviation is undefined otherwise.

I have written some code but keep that I thought should work but keep failing test cases.
Please review my code an help guide me to a solution.

public static double stdev(int a[]){
		double mean = 0; 
		int sum = 0;
	    //1. Work out the Mean (the simple average of the numbers)
	    for (int i = 0; i < a.length; i++) {
			
			sum += a[i];
			if(i == a.length -1){
				mean = sum/a.length;
			}
		}
	   
	    
	    //2. Then for each number: subtract the Mean and square the result
	    //GET DIFFERENCE
	    double variance = 0;
	    double [] b = new double [a.length];
	    for (int i = 0; i < a.length; i++) {
			//b[i] = Math.sqrt(Math.abs(a[i] - mean));
	    	double diff = Math.abs(a[i] - mean);
	    	b[i] = diff * diff;
		}
	    
	    //3. Then work out the mean of those squared differences.
	   
	    for (int i = 0; i < b.length; i++) {
			variance += b[i]/b.length;
		}
	    
	     
	    //4. Take the square root of that and you are done!
	    double standardDeviation = Math.sqrt(Math.ceil(variance));
	    return  standardDeviation;
	}

Open in new window


I tried following this algorithm/formula:
http://www.mathsisfun.com/data/standard-deviation.html

I appreciate your help.
0
Comment
Question by:DOCDGA
  • 3
  • 2
  • 2
7 Comments
 
LVL 14

Expert Comment

by:Geisrud
ID: 39850689
I'm no Java expert, but I do have some practice - we can make this a learning exercise for the both of us.  I thought I would toss this first post up as I work through your code.

So, step by step, the first problem I see is your mean result.  You set the mean type to a double (good), but you're finding the result by dividing an int by an int.  That means your result will discard anything after the decimal.  You get a value plus a ".0" in this case, your mean is "2.0".  I always like to toss in a print statement as I code to check that my result is what I expect.

System.out.println("Average = " + mean); //to see value of mean
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39850696
You're off on the wrong foot. The calculation of the mean is wrong. I haven't looked beyond that.
a. Don't do the division until the loop is finished
b. (and more importantly) 'sum' should be a double. Why?

UPDATE: i see someone's told you why ;)
0
 

Author Comment

by:DOCDGA
ID: 39850754
Okay, I have changed sum to a double and cast my divisor to a double.
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 14

Accepted Solution

by:
Geisrud earned 500 total points
ID: 39850904
In your step 2 code, I would take out the "Math.abs" function.  I get the same result either way, and this may be my rudimentary understanding of standard deviation, but I don't think there's any reference to absolute value in there.

So - I used:
double diff = a[i] - mean;

Open in new window


Lastly, and most importantly, there are two ways to calculate standard deviation (WTF!?!?!).  I'm guessing your result is ~10.66, but you're "supposed" to be getting 11.237.  This is because one way is figuring for a "sample" population, while the other figures for the entire data set.

This article may help explain that better than I ever could.
http://chemistry.about.com/od/mathsciencefundamentals/a/How-To-Calculate-Standard-Deviation.htm

Suffice it to say, you need to adjust one other line of your code to get the answer they want.  In your step 3, make the change:

variance += b[i]/(b.length-1);

Open in new window

0
 

Author Closing Comment

by:DOCDGA
ID: 39850936
Thanks for your assistance. I had been working on this problem for awhile.
0
 
LVL 14

Expert Comment

by:Geisrud
ID: 39850972
Glad to help - and I learned something along the way too!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 39851113
and cast my divisor to a double.
Actually that's not necessary
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
This article provides a brief introduction to tissue engineering, the process by which organs can be grown artificially. It covers the problems with organ transplants, the tissue engineering process, and the current successes and problems of the tec…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question