This repository has been archived by the owner on Dec 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Statistics2.java
87 lines (74 loc) · 2.47 KB
/
Statistics2.java
1
2
3
4
5
6
7
8
9
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package hw;
// James Ding
public class Statistics2 {
double[] array;
public Statistics2(int size) {
array = new double[size];
boolean lock = false;
double[] prevBoxMuller = xyBoxMuller();
for (int i = 0; i < size; i++) {
if (lock) {
array[i] = prevBoxMuller[1];
} else {
double[] boxMuller = xyBoxMuller();
array[i] = boxMuller[0];
prevBoxMuller = boxMuller;
}
lock = !lock;
}
}
public static double[] xyBoxMuller() {
double u = Math.random(), v = Math.random();
// Use box-muller method to generate random points that are normally distributed
double sqrt = Math.sqrt(-2 * Math.log(u));
double x = sqrt * Math.cos(2 * Math.PI * v);
double y = sqrt * Math.sin(2 * Math.PI * v);
return new double[]{x, y};
}
public static String stringDotPlot(int[] dotPlot) {
StringBuilder sb = new StringBuilder();
int max = 0;
for (int i : dotPlot) {
if (i > max) max = i;
}
for (int movingMax = max; movingMax > 0; movingMax--) {
for (int i : dotPlot) {
if (i >= movingMax) sb.append("*");
else sb.append(" ");
}
sb.append("\n");
}
for (int i = 0; i < dotPlot.length; i++) sb.append("-");
return sb.toString();
}
public static void main(String[] args) {
Statistics2 s = new Statistics2(100);
System.out.format("Mean: %.2f Standard Deviation: %.2f\n", s.mean(), s.standardDeviation());
System.out.println(stringDotPlot(s.dotPlot(-6, 6, 0.1)));
}
public double mean() {
double sum = 0;
for (double d : array) {
sum += d;
}
return sum / array.length;
}
public double standardDeviation() {
double mean = mean();
double sum = 0;
for (double d : array) {
sum += Math.pow(d - mean, 2);
}
return Math.sqrt(sum / (array.length - 1));
}
public int[] dotPlot(double min, double max, double density) {
double distance = Math.abs(max - min);
int partitions = (int) (distance / density);
int[] dotPlot = new int[partitions];
for (double d : array) {
if (d < min || d > max) continue;
dotPlot[(int) ((d - min) / density)]++;
}
return dotPlot;
}
}