Reputation: 1
Ok so i have a code set out to get the mean of an array that has upto 50 elements, i want to also find the standard deviation of those elements and show it right under where it would display the mean, my code so far is
import java.util.Scanner;
public class caArray
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("How many numbers you want to calculate average upto 50 : ");
int n = input.nextInt();
int[] array = new int[50];
int sum = 0;
for (int m = 0; m < n; m++)
{
System.out.print("Number " + m + " : ");
array[m] = input.nextInt();
}
for (int m = 0; m < n; m++)
{
sum = array[m] + sum;
}
{
System.out.println("Total value of Numbers = " + sum);
}
{
double avg;
avg = sum / array.length;
System.out.println("Average of Numbers = " + avg); //calculate average value
}
}
}
i need to add into this to get the standard deviation in the one program
EDIT** I cannot use the functions as i actully have to use the standard deviation fourmula withing the program itself
Upvotes: 0
Views: 2470
Reputation: 7357
you can write it in 3 Methods
private double standardDeviation(double[] input) {
return Math.sqrt(variance(input));
}
private double variance(double[] input) {
double expectedVal = expectedValue(input);
double variance = 0;
for(int i = 0;i<input.length;++i) {
double buffer = input[i] - expectedVal;
variance += buffer * buffer;
}
return variance;
}
private double expectedValue(double[] input) {
double sum = 0;
for(int i = 0;i<input.length;++i) {
sum += input[i];
}
return sum/input.length;
}
hope it works, i am not quite shure about it, if i used the formulas the right way.
But basicly you have this 3 mathematical formulas in your calculation
Upvotes: 1
Reputation: 272347
If you don't have to write it yourself, check out Apache Commons Math. The stats documentation references how to derive standard deviations.
As you have to write it yourself, perhaps checking out the source code for DescriptiveStatistics would be instructive (look for the function getStandardDeviation()
)
Upvotes: 0