English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn to use functions in Kotlin to calculate the standard deviation.
This program uses an array to calculate the standard deviation of a single series.
To calculate the standard deviation, the function calculateSD() will be created. It includes10an array of elements will be passed to the function, which will calculate the standard deviation and return it to the main() function.
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) }
The output when running the program is:
Standard Deviation = 2.872281
In the above program, we usedMath.pow()andMath.sqrt()help to calculate powers and square roots separately.
This is the equivalent Java code:Java Program to Calculate Standard Deviation.