Sling Academy
Home/Rust/Calculating Variance and Standard Deviation in Rust

Calculating Variance and Standard Deviation in Rust

Last updated: January 03, 2025

In this article, we'll walk through how to calculate variance and standard deviation in Rust. These are statistical measures used to describe the spread or dispersion of a set of values. Understanding how to implement these calculations can be quite valuable for anyone interested in data processing or statistical programming in Rust.

Understanding Variance and Standard Deviation

Variance measures how far a set of numbers are spread out from their average value. It's calculated as the average of the squared differences from the mean. On the other hand, standard deviation is the square root of variance, providing a measure of the spread of a set of numbers in their original units.

Formulas:

  • Variance (σ²): $$\sigma^2 = \frac{\sum{(x_i - \mu)^2}}{N}$$ where \(x_i\) is each individual value, \(\mu\) is the mean, and \(N\) is the number of values.
  • Standard Deviation (σ): $$\sigma = \sqrt{\sigma^2}$$

Implementing in Rust

Let's dive into some Rust code to implement these calculations. We'll begin by installing Rust if it's not already available on your system:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Once Rust is installed, you can create a new Rust project:

cargo new statistics --bin
cd statistics

Open the main.rs file and start by including necessary parts:

fn main() {
    let data = vec![1.0, 2.0, 3.0, 4.0, 5.0];

    let variance = calculate_variance(&data);
    let std_deviation = calculate_standard_deviation(&data);

    println!("Variance: {}", variance);
    println!("Standard Deviation: {}", std_deviation);
}

Next, we implement the two functions to calculate variance and standard deviation.

Calculating Variance

To calculate the variance, we first need to compute the mean and then use it to determine how each value differs from it.

fn calculate_variance(data: &Vec<f64>) -> f64 {
    let mean = data.iter().sum::() / data.len() as f64;    
    let variance = data.iter().map(|value| {
        let diff = mean - (*value as f64);
        diff * diff
    }).sum::() / data.len() as f64;
    variance
}

Calculating Standard Deviation

The standard deviation is simply the square root of the variance calculated.

fn calculate_standard_deviation(data: &Vec<f64>) -> f64 {
    let variance = calculate_variance(data);
    variance.sqrt()
}

With these implementations, running the main.rs file should output the variance and standard deviation for the provided dataset. Compile and run the application with:

cargo run

Conclusion

In this tutorial, we demonstrated how to calculate variance and standard deviation using the Rust programming language. Rust’s powerful and efficient computation abilities make it a great choice for statistical and mathematical calculations. Through step-by-step demonstrations, you now have foundational methods to further expand or integrate into larger data analysis projects. Happy coding with Rust!

Next Article: Implementing Linear Regression in Rust with Basic Math Operations

Previous Article: Exploring Statistical Functions: Mean, Median, Mode in Rust

Series: Math and Numbers in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior