The title is pretty self explanatory of my issue.
I am trying to write a program which will calculate the standard deviation of a set of numbers input by the user.
This was a lot tougher than I had anticipated and writing the algorithm for it has been a pain.
Any assistance would be greatly appreciated!
import java.util.Scanner;
public class StandardDeviation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double num;
double total;
int n;
System.out.print("First Number: ");
num = input.nextDouble();
n = 0;
total = 0;
while ( num != -1 ) {
n++;
total += num;
System.out.print("Next Number: ");
num = input.nextDouble();
}
double mean;
double dev;
double devn;
double sqrt;
mean = total/n;
dev = (total - mean);
devn = dev/n;
sqrt = Math.sqrt(devn);
System.out.println("N= " +n);
System.out.println("Total= " +total);
System.out.println("Mean= " +mean);
System.out.println("Deviation= " +dev);
System.out.print("The standard deviation is: " +sqrt);
}
}
That is because your algorithm is wrong. You cannot compute standard deviation by accumulating your samples alone. You must also accumulate their squares.
Like this:
n = 0;
total = 0;
total_squared = 0;
while ( num != -1 ) {
n++;
total += num;
total_squared += num*num;
System.out.print("Next Number: ");
num = input.nextDouble();
}
Your solution will be:
mean = total/n;
stddev = sqrt(total_squared/n - mean*mean);
Here is how you calculate standard deviation with some sample data.
double[] a = {10, 20, 30};
double total = 0;
for (double i : a) {
total += i;
}
double mean = total/a.length;
double sqTot = 0;
for (double i : a) {
sqTot += Math.pow((i-mean), 2);
}
System.out.println("Standard deviation " + Math.sqrt(sqTot/a.length));
The formula for standard deviation is wrong. This will do:
n = 0;
total = 0;
total_sq = 0;
while ( num != -1 ) {
n++;
total += num;
total_sq += num*num;
System.out.print("Next Number: ");
num = input.nextDouble();
}
For population standard deviation:
mean = total/n;
dev_p = sqrt(total_sq/n - mean*mean);
For sample standard deviatiod:
dev_s = dev_p * n/(n-1);
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.