First, just for reference: "
standard deviation" is a
second moment of
distribution:
http://en.wikipedia.org/wiki/Standard_deviation[
^],
http://en.wikipedia.org/wiki/Moment_%28mathematics%29[
^],
http://en.wikipedia.org/wiki/Distribution_%28mathematics%29[
^].
Let's check up: you correctly populate the distribution
Range
(hard-coded
immediate constants 4, 10 and 50 is really bad thing, I hope you replace it in near future with explicitly declared constants or variable; to your credit, I appreciate that at least you never write any such constants twice), you correctly calculate individual deviations for each value.
From this point, you do it wrong. You need to summarize the individual deviations (squared) in the loop (also use
foreach
, no need to use
for
), then you need to take a square root of the sum of squared deviations,
after the cycle, but you did it in the cycle. You also
should not touch total
calculate in the previous loop. You don't need it after
avg
is calculated. This is a bug.
So, in your last loop you should do this:
double sum = 0;
foreach(double value in Temp) {
double dev = value - avg;
sum += dev * dev;
}
float standardDeviation = Math.Sqrt(sum);
Problem solved.
Some side recommendations: 1) never try to do all the work in your entry point (
Main
), white a separate class and methods; 2) don't use such short variable names like "
i
", even if this is a loop variable; use something semantic:
index
,
value
,
counter
,
element
… 3) use the Debugger on any slightest concern about your run-time behavior; at least make sure you do it before asking questions like this one.
[EDIT]
Lan Fan found another bug: you put
ReadLine
in the loop. Maybe, this is not a mistake, but it could prevent you from seeing what's going on.
Nevertheless, my solution I've written above was correct in first place.
Again, don't use I/O for such a simple debugging, use the Debugger.
—SA