SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arrays
Exercise:
Exercises
Question:6 | ISBN:9780136091813 | Edition: 2

Question

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:




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 .

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of stdev method:

	public static double stdev(int[] a)
	{
		if(a.length == 0)
			return 0;
		
		double total = 0;
		for(int i = 0; i < a.length; i++)
		{
			total += a[i];
		}
		
		double average = total / a.length;		

		total = 0;
		for(int i = 0; i < a.length; i++)
		{
			total += Math.pow((a[i] - average), 2.0);
		}

		double sdv = Math.sqrt(total / (a.length - 1));
		return sdv;
	}
0 0

Discussions

Post the discussion to improve the above solution.