Skip to content

Commit 1ec81b1

Browse files
committed
Add standard deviation
1 parent 6722934 commit 1ec81b1

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/summary_statistics/means.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ where
5454
Ok(central_moments[3] / central_moments[2].sqrt().powi(3))
5555
}
5656

57+
fn standard_deviation(&self) -> Result<A, EmptyInput>
58+
where
59+
A: Float + FromPrimitive
60+
{
61+
Ok(self.central_moment(2)?.sqrt())
62+
}
63+
5764
fn central_moment(&self, order: u16) -> Result<A, EmptyInput>
5865
where
5966
A: Float + FromPrimitive,
@@ -277,6 +284,18 @@ mod tests {
277284
assert_eq!(a.central_moment(1).unwrap(), 0.);
278285
}
279286

287+
#[test]
288+
fn test_standard_deviation() {
289+
let a: Array1<f64> = array![4.0, 9.0, 11.0, 12.0, 17.0, 5.0, 8.0, 12.0, 14.0];
290+
// Computed using numpy.std
291+
let expected_std = 3.9377878103709665;
292+
assert_abs_diff_eq!(
293+
a.standard_deviation().unwrap(),
294+
expected_std,
295+
epsilon = 1e-12
296+
);
297+
}
298+
280299
#[test]
281300
fn test_central_moments() {
282301
let a: Array1<f64> = array![

src/summary_statistics/mod.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,24 @@ where
101101
where
102102
A: Float + FromPrimitive;
103103

104+
/// Returns the [standard deviation] σ of all elements in the array:
105+
/// ```text
106+
/// _____________
107+
/// / 1 n
108+
/// σ = / ― ∑ (xᵢ-x̅)²
109+
/// √ n i=1
110+
/// ```
111+
///
112+
/// If the array is empty, `Err(EmptyInput)` is returned.
113+
///
114+
/// **Panics** if `A::from_usize()` fails to convert the number of elements
115+
/// in the array or if `order` overflows `i32`.
116+
///
117+
/// [standard deviation]: https://en.wikipedia.org/wiki/Standard_deviation
118+
fn standard_deviation(&self) -> Result<A, EmptyInput>
119+
where
120+
A: Float + FromPrimitive;
121+
104122
/// Returns the *p*-th [central moment] of all elements in the array, μₚ:
105123
///
106124
/// ```text

0 commit comments

Comments
 (0)