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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
macro_rules! impl_harmonic_mean {
($name:ident, $ty:ty) => {
/// Online harmonic mean.
///
/// Tracks the sum of reciprocals for computing the harmonic mean
/// incrementally. Useful for averaging rates (e.g., throughput in
/// requests/second across multiple servers).
///
/// # Use Cases
/// - Average throughput across heterogeneous servers
/// - Mean speed over equal-distance segments
/// - Any rate where arithmetic mean would be misleading
#[derive(Debug, Clone)]
pub struct $name {
reciprocal_sum: $ty,
count: u64,
}
impl $name {
/// Creates a new empty accumulator.
#[inline]
#[must_use]
pub const fn new() -> Self {
Self {
reciprocal_sum: 0.0 as $ty,
count: 0,
}
}
/// Feeds a sample. Must be positive and non-zero.
///
/// # Panics
///
/// Panics if sample is zero or negative.
#[inline]
pub fn update(&mut self, sample: $ty) {
assert!(
sample > 0.0 as $ty,
"harmonic mean requires positive values"
);
self.count += 1;
self.reciprocal_sum += 1.0 as $ty / sample;
}
/// Harmonic mean, or `None` if empty.
#[inline]
#[must_use]
pub fn mean(&self) -> Option<$ty> {
if self.count == 0 {
Option::None
} else {
Option::Some(self.count as $ty / self.reciprocal_sum)
}
}
/// Number of samples processed.
#[inline]
#[must_use]
pub fn count(&self) -> u64 {
self.count
}
/// Resets to empty state.
#[inline]
pub fn reset(&mut self) {
self.reciprocal_sum = 0.0 as $ty;
self.count = 0;
}
}
impl Default for $name {
#[inline]
fn default() -> Self {
Self::new()
}
}
};
}
impl_harmonic_mean!(HarmonicMeanF64, f64);
impl_harmonic_mean!(HarmonicMeanF32, f32);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty() {
let hm = HarmonicMeanF64::new();
assert!(hm.mean().is_none());
}
#[test]
fn known_values() {
let mut hm = HarmonicMeanF64::new();
// HM(1, 4) = 2 / (1/1 + 1/4) = 2 / 1.25 = 1.6
hm.update(1.0);
hm.update(4.0);
let m = hm.mean().unwrap();
assert!((m - 1.6).abs() < 1e-10, "expected 1.6, got {m}");
}
#[test]
fn harmonic_leq_arithmetic() {
let mut hm = HarmonicMeanF64::new();
let vals = [2.0, 4.0, 8.0];
let mut sum = 0.0;
for &v in &vals {
hm.update(v);
sum += v;
}
let arithmetic = sum / vals.len() as f64;
let harmonic = hm.mean().unwrap();
assert!(
harmonic <= arithmetic,
"HM ({harmonic}) should be <= AM ({arithmetic})"
);
}
#[test]
fn equal_values() {
let mut hm = HarmonicMeanF64::new();
for _ in 0..100 {
hm.update(5.0);
}
let m = hm.mean().unwrap();
assert!(
(m - 5.0).abs() < 1e-10,
"HM of equal values should equal that value"
);
}
#[test]
fn reset() {
let mut hm = HarmonicMeanF64::new();
hm.update(1.0);
hm.reset();
assert_eq!(hm.count(), 0);
assert!(hm.mean().is_none());
}
#[test]
fn f32_basic() {
let mut hm = HarmonicMeanF32::new();
hm.update(2.0);
hm.update(4.0);
assert!(hm.mean().is_some());
}
#[test]
fn default_is_empty() {
let hm = HarmonicMeanF64::default();
assert_eq!(hm.count(), 0);
}
#[test]
#[should_panic(expected = "positive values")]
fn panics_on_zero() {
let mut hm = HarmonicMeanF64::new();
hm.update(0.0);
}
}