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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct Skewness {
avg: MeanWithError,
sum_3: f64,
}
impl Skewness {
#[inline]
pub fn new() -> Skewness {
Skewness {
avg: MeanWithError::new(),
sum_3: 0.,
}
}
#[inline]
fn increment(&mut self) {
self.avg.increment();
}
#[inline]
fn add_inner(&mut self, delta: f64, delta_n: f64) {
let n = self.len().to_f64().unwrap();
let term = delta * delta_n * (n - 1.);
self.sum_3 += term * delta_n * (n - 2.)
- 3.*delta_n * self.avg.sum_2;
self.avg.add_inner(delta_n);
}
#[inline]
pub fn is_empty(&self) -> bool {
self.avg.is_empty()
}
#[inline]
pub fn mean(&self) -> f64 {
self.avg.mean()
}
#[inline]
pub fn len(&self) -> u64 {
self.avg.len()
}
#[inline]
pub fn sample_variance(&self) -> f64 {
self.avg.sample_variance()
}
#[inline]
pub fn population_variance(&self) -> f64 {
self.avg.population_variance()
}
#[inline]
pub fn error_mean(&self) -> f64 {
self.avg.error()
}
#[inline]
pub fn skewness(&self) -> f64 {
if self.sum_3 == 0. {
return 0.;
}
let n = self.len().to_f64().unwrap();
let sum_2 = self.avg.sum_2;
debug_assert_ne!(sum_2, 0.);
n.sqrt() * self.sum_3 / (sum_2*sum_2*sum_2).sqrt()
}
}
impl Default for Skewness {
fn default() -> Skewness {
Skewness::new()
}
}
impl Estimate for Skewness {
#[inline]
fn add(&mut self, x: f64) {
let delta = x - self.mean();
self.increment();
let n = self.len().to_f64().unwrap();
self.add_inner(delta, delta/n);
}
#[inline]
fn estimate(&self) -> f64 {
self.skewness()
}
}
impl Merge for Skewness {
#[inline]
fn merge(&mut self, other: &Skewness) {
let len_self = self.len().to_f64().unwrap();
let len_other = other.len().to_f64().unwrap();
let len_total = len_self + len_other;
let delta = other.mean() - self.mean();
let delta_n = delta / len_total;
self.sum_3 += other.sum_3
+ delta*delta_n*delta_n * len_self*len_other*(len_self - len_other)
+ 3.*delta_n * (len_self * other.avg.sum_2 - len_other * self.avg.sum_2);
self.avg.merge(&other.avg);
}
}
impl_from_iterator!(Skewness);
impl_from_par_iterator!(Skewness);