How to resolve the algorithm Cumulative standard deviation step by step in the Rust programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Cumulative standard deviation step by step in the Rust programming language

Table of Contents

Problem Statement

Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used. Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.

Use this to compute the standard deviation of this demonstration set,

{ 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 }

{\displaystyle {2,4,4,4,5,5,7,9}}

, which is

2

{\displaystyle 2}

.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Cumulative standard deviation step by step in the Rust programming language

Source code in the rust programming language

pub struct CumulativeStandardDeviation {
    n: f64,
    sum: f64,
    sum_sq: f64
}

impl CumulativeStandardDeviation {
    pub fn new() -> Self {
        CumulativeStandardDeviation {
            n: 0.,
            sum: 0.,
            sum_sq: 0.
        }
    }

    fn push(&mut self, x: f64) -> f64 {
        self.n += 1.;
        self.sum += x;
        self.sum_sq += x * x;

        (self.sum_sq / self.n - self.sum * self.sum / self.n / self.n).sqrt()
    }
}

fn main() {
    let nums = [2, 4, 4, 4, 5, 5, 7, 9];

    let mut cum_stdev = CumulativeStandardDeviation::new();
    for num in nums.iter() {
        println!("{}", cum_stdev.push(*num as f64));
    }
}


fn sd_creator() -> impl FnMut(f64) -> f64 {
    let mut n = 0.0;
    let mut sum = 0.0;
    let mut sum_sq = 0.0;
    move |x| {
        sum += x;
        sum_sq += x*x;
        n += 1.0;
        (sum_sq / n - sum * sum / n / n).sqrt()
    }
}

fn main() {
    let nums = [2, 4, 4, 4, 5, 5, 7, 9];

    let mut sd_acc = sd_creator();
    for num in nums.iter() {
        println!("{}", sd_acc(*num as f64));
    }
}


  

You may also check:How to resolve the algorithm Longest common substring step by step in the SETL programming language
You may also check:How to resolve the algorithm Handle a signal step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Radical of an integer step by step in the Raku programming language
You may also check:How to resolve the algorithm Topswops step by step in the Haskell programming language
You may also check:How to resolve the algorithm I before E except after C step by step in the Lua programming language