Skip to content

Add standard deviation #43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/summary_statistics/means.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,13 @@ where
Ok(central_moments[3] / central_moments[2].sqrt().powi(3))
}

fn standard_deviation(&self) -> Result<A, EmptyInput>
where
A: Float + FromPrimitive,
{
Ok(self.central_moment(2)?.sqrt())
}

fn central_moment(&self, order: u16) -> Result<A, EmptyInput>
where
A: Float + FromPrimitive,
Expand Down Expand Up @@ -277,6 +284,18 @@ mod tests {
assert_eq!(a.central_moment(1).unwrap(), 0.);
}

#[test]
fn test_standard_deviation() {
let a: Array1<f64> = array![4.0, 9.0, 11.0, 12.0, 17.0, 5.0, 8.0, 12.0, 14.0];
// Computed using numpy.std
let expected_std = 3.9377878103709665;
assert_abs_diff_eq!(
a.standard_deviation().unwrap(),
expected_std,
epsilon = 1e-12
);
}

#[test]
fn test_central_moments() {
let a: Array1<f64> = array![
Expand Down
18 changes: 18 additions & 0 deletions src/summary_statistics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,24 @@ where
where
A: Float + FromPrimitive;

/// Returns the [standard deviation] σ of all elements in the array:
/// ```text
/// _____________
/// / 1 n
/// σ = / ― ∑ (xᵢ-x̅)²
/// √ n i=1
/// ```
///
/// If the array is empty, `Err(EmptyInput)` is returned.
///
/// **Panics** if `A::from_usize()` fails to convert the number of elements
/// in the array or if `order` overflows `i32`.
///
/// [standard deviation]: https://en.wikipedia.org/wiki/Standard_deviation
fn standard_deviation(&self) -> Result<A, EmptyInput>
where
A: Float + FromPrimitive;

/// Returns the *p*-th [central moment] of all elements in the array, μₚ:
///
/// ```text
Expand Down