Kotlin Program to Calculate Standard Deviation

This program calculates the standard deviation of a individual series using arrays. Visit this page to learn about Standard Deviation.

To calculate the standard deviation, calculateSD() function is created. The array containing 10 elements is passed to the function and this function calculates the standard deviation and returns it to the main() function.

Example: Program to Calculate Standard Deviation

fun main(args: Array<String>) {
    val numArray = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
    val SD = calculateSD(numArray)

    System.out.format("Standard Deviation = %.6f", SD)
}

fun calculateSD(numArray: DoubleArray): Double {
    var sum = 0.0
    var standardDeviation = 0.0

    for (num in numArray) {
        sum += num
    }

    val mean = sum / 10

    for (num in numArray) {
        standardDeviation += Math.pow(num - mean, 2.0)
    }

    return Math.sqrt(standardDeviation / 10)
}

When you run the program, the output will be:

Standard Deviation = 2.872281

In the above program, we've used the help of Math.pow() and Math.sqrt() to calculate the power and square root respectively.

Here's the equivalent Java code: Java program to calculate standard deviation.

Did you find this article helpful?