01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package algs13;
import stdlib.*;
/* ***********************************************************************
* Compilation: javac Stats.java
* Execution: java Stats < input.txt
* Dependencies: Bag.java StdIn.java StdOut.java
*
* Reads in a sequence of real numbers from standard input and
* computes their mean and standard deviation.
*
* % java Stats
* 100 99 101 120 98 107 109 81 101 90
* Mean: 100.60
* Std dev: 10.51
*
*************************************************************************/
public class XStats {
public static void main(String[] args) {
// read in numbers
Bag<Double> numbers = new Bag<>();
while (!StdIn.isEmpty()) {
numbers.add(StdIn.readDouble());
}
int N = numbers.size();
// compute mean
double sum = 0.0;
for (double x : numbers)
sum += x;
double mean = sum/N;
// compute standard deviation
sum = 0.0;
for (double x : numbers) {
sum += (x - mean) * (x - mean);
}
double std = Math.sqrt(sum/(N-1));
StdOut.format("Mean: %.2f\n", mean);
StdOut.format("Std dev: %.2f\n", std);
}
}
|