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,948 questions

51,890 answers

573 users

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

1 Answer

0 votes
import Foundation

func calculateMean(_ data: [Double]) -> Double {
    guard !data.isEmpty else { return 0.0 }
    
    let sum = data.reduce(0, +)
    
    return sum / Double(data.count)
}

func calculateStandardDeviation(_ data: [Double], mean: Double) -> Double {
    guard data.count > 1 else { return 0.0 }
    
    let sumOfSquaredDiffs = data.map { pow($0 - mean, 2) }.reduce(0, +)
    let variance = sumOfSquaredDiffs / Double(data.count - 1)
    
    return sqrt(variance)
}

let numbers: [Double] = [3.4, 1.8, 4.3, 5.0, 6.2]

let mean = calculateMean(numbers)
let stddev = calculateStandardDeviation(numbers, mean: mean)

print(String(format: "Mean: %.2f", mean))
print(String(format: "Standard Deviation: %.2f", stddev))



/*
run:

Mean: 4.14
Standard Deviation: 1.66

*/

 



answered Jun 30, 2025 by avibootz
...