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

Calculating Variance and Standard Deviation in Kotlin

Last updated: November 30, 2024

Introduction

Variance and standard deviation are important concepts in statistics used to measure the variability or dispersion in a dataset. In this article, we'll learn how to calculate these in the Kotlin programming language. This guide will walk you through understanding these concepts and applying them using Kotlin's powerful programming features.

Understanding the Concepts

  • Variance: It measures how much the numbers in a set differ from the average of the set.
  • Standard Deviation: It is the square root of the variance, providing a measure of the average distance from the mean.

Steps to Calculate Variance and Standard Deviation

Here are the basic steps that you can follow to calculate variance and standard deviation:

  1. Find the mean (average) of the dataset.
  2. Subtract the mean from each number to get the deviation of each number.
  3. Square each deviation.
  4. Find the mean of these squared deviations. This value is the variance.
  5. Take the square root of the variance to get the standard deviation.

Implementation in Kotlin

Now, let’s implement these steps in Kotlin.

Calculating the Mean


fun calculateMean(numbers: List): Double {
    return numbers.average()
}

This simple function takes a list of numbers and returns their average using Kotlin's built-in average() function.

Calculating the Variance


fun calculateVariance(numbers: List, mean: Double): Double {
    val squaredDifferences = numbers.map { number -> (number - mean) * (number - mean) }
    return squaredDifferences.average()
}

Here, we map each number to its squared difference from the mean and then find the average of these squared differences.

Calculating the Standard Deviation


fun calculateStandardDeviation(variance: Double): Double {
    return Math.sqrt(variance)
}

This function simply takes the square root of the variance using Kotlin’s Math.sqrt() function.

Complete Code Example

Let’s see how these functions can come together in a complete Kotlin program:


fun main() {
    val numbers = listOf(10.0, 12.0, 23.0, 23.0, 16.0, 23.0, 21.0, 16.0)
    val mean = calculateMean(numbers)
    val variance = calculateVariance(numbers, mean)
    val standardDeviation = calculateStandardDeviation(variance)

    println("Mean: $mean")
    println("Variance: $variance")
    println("Standard Deviation: $standardDeviation")
}

fun calculateMean(numbers: List): Double {
    return numbers.average()
}

fun calculateVariance(numbers: List, mean: Double): Double {
    val squaredDifferences = numbers.map { number -> (number - mean) * (number - mean) }
    return squaredDifferences.average()
}

fun calculateStandardDeviation(variance: Double): Double {
    return Math.sqrt(variance)
}

Running this program will compute the mean, variance, and standard deviation of the provided list of numbers and print the results to the console.

Conclusion

In this article, we explored how to calculate variance and standard deviation using Kotlin. These mathematical operations are crucial for data analysis tasks. Kotlin's expressive syntax and functional features make it a great choice for statistical computations.

Next Article: Using `reduce` and `fold` for Custom Aggregations in Kotlin

Previous Article: Performing Aggregations in Kotlin: Sum, Count, and Average

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin