nu_command/math/
stddev.rs

1use super::variance::compute_variance as variance;
2use crate::math::utils::run_with_function;
3use nu_engine::command_prelude::*;
4
5#[derive(Clone)]
6pub struct MathStddev;
7
8impl Command for MathStddev {
9    fn name(&self) -> &str {
10        "math stddev"
11    }
12
13    fn signature(&self) -> Signature {
14        Signature::build("math stddev")
15            .input_output_types(vec![
16                (Type::List(Box::new(Type::Number)), Type::Number),
17                (Type::table(), Type::record()),
18                (Type::record(), Type::record()),
19            ])
20            .switch(
21                "sample",
22                "calculate sample standard deviation (i.e. using N-1 as the denominator)",
23                Some('s'),
24            )
25            .allow_variants_without_examples(true)
26            .category(Category::Math)
27    }
28
29    fn description(&self) -> &str {
30        "Returns the standard deviation of a list of numbers, or of each column in a table."
31    }
32
33    fn search_terms(&self) -> Vec<&str> {
34        vec![
35            "SD",
36            "standard",
37            "deviation",
38            "dispersion",
39            "variation",
40            "statistics",
41        ]
42    }
43
44    fn is_const(&self) -> bool {
45        true
46    }
47
48    fn run(
49        &self,
50        engine_state: &EngineState,
51        stack: &mut Stack,
52        call: &Call,
53        input: PipelineData,
54    ) -> Result<PipelineData, ShellError> {
55        let sample = call.has_flag(engine_state, stack, "sample")?;
56        run_with_function(call, input, compute_stddev(sample))
57    }
58
59    fn run_const(
60        &self,
61        working_set: &StateWorkingSet,
62        call: &Call,
63        input: PipelineData,
64    ) -> Result<PipelineData, ShellError> {
65        let sample = call.has_flag_const(working_set, "sample")?;
66        run_with_function(call, input, compute_stddev(sample))
67    }
68
69    fn examples(&self) -> Vec<Example> {
70        vec![
71            Example {
72                description: "Compute the standard deviation of a list of numbers",
73                example: "[1 2 3 4 5] | math stddev",
74                result: Some(Value::test_float(std::f64::consts::SQRT_2)),
75            },
76            Example {
77                description: "Compute the sample standard deviation of a list of numbers",
78                example: "[1 2 3 4 5] | math stddev --sample",
79                result: Some(Value::test_float(1.5811388300841898)),
80            },
81            Example {
82                description: "Compute the standard deviation of each column in a table",
83                example: "[[a b]; [1 2] [3 4]] | math stddev",
84                result: Some(Value::test_record(record! {
85                    "a" => Value::test_int(1),
86                    "b" => Value::test_int(1),
87                })),
88            },
89        ]
90    }
91}
92
93pub fn compute_stddev(sample: bool) -> impl Fn(&[Value], Span, Span) -> Result<Value, ShellError> {
94    move |values: &[Value], span: Span, head: Span| {
95        // variance() produces its own usable error, so we can use `?` to propagated the error.
96        let variance = variance(sample)(values, span, head)?;
97        let val_span = variance.span();
98        match variance {
99            Value::Float { val, .. } => Ok(Value::float(val.sqrt(), val_span)),
100            Value::Int { val, .. } => Ok(Value::float((val as f64).sqrt(), val_span)),
101            other => Ok(other),
102        }
103    }
104}
105
106#[cfg(test)]
107mod test {
108    use super::*;
109
110    #[test]
111    fn test_examples() {
112        use crate::test_examples;
113
114        test_examples(MathStddev {})
115    }
116}