Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to calculate the mean and the standard deviation of a sequence of floating-point values in Kotlin

1 Answer

0 votes
fun calculateMean(data: List<Double>): Double {
    if (data.isEmpty()) return 0.0
    
    return data.sum() / data.size
}

fun calculateStandardDeviation(data: List<Double>, mean: Double): Double {
    if (data.size < 2) return 0.0

    val sumOfSquaredDiffs = data.sumOf { (it - mean) * (it - mean) }
    val variance = sumOfSquaredDiffs / (data.size - 1)
    
    return kotlin.math.sqrt(variance)
}

fun main() {
    val numbers = listOf(3.4, 1.8, 4.3, 5.0, 6.2)
    
    val mean = calculateMean(numbers)
    val stddev = calculateStandardDeviation(numbers, mean)

    println("Mean: %.2f".format(mean))
    println("Standard Deviation: %.2f".format(stddev))
}

 
  
/*
run:
  
Mean: 4.14
Standard Deviation: 1.66

*/

 



answered Jun 30, 2025 by avibootz
...