The standard deviation is the measure of how spread out numbers are. Its symbol is sigma( σ ). It is the square root of variance. The task is to calculate the standard deviation of some numbers.
Consider an example that consists of 6 numbers and then to calculate the standard deviation, first we need to calculate the sum of 6 numbers, and then the mean will be calculated. Then the standard deviation will be calculated using the standard deviation formula.
Standard deviation = square root of ∑(Xi - ų)2 / N where, Xi = each element of the array ų = mean of the elements of the array N = Number of elements ∑ = Sum of the each element
Input : [12, 32, 11, 55, 10, 23, 14, 30] Output : 14.438988 Input : [10, 12, 22, 34, 21] Output : 8.541663
Approach: Using Mathematical Formula
- First, create a class called calculateSD2
- Then create the main method and then in the main method create an object of the above class and call it using the object.
- Then declare an array in this class with the values given in the above example.
- Now, in order to iterate through the array, we need to find the size of the array.
- Now, use the for-loop and iterate through this array and increment it by 1 as we need to print all the elements of the array.
- Then, again use the for-loop and iterate through the array in order to calculate the sum of the elements of the array.
- After that, the mean will be calculated by mean = sum / n, where n is the number of elements in the array.
- Now, the standard deviation will be calculated with the help of mean, which is done by iterating through for-loop again and with the help of Mathematical predefined methods like Math.pow and Math.sqrt.
- After that, the value will be returned by that class and then print.
Elements are: 12 32 11 55 10 23 14 30 Standard Deviation = 14.438988
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.