How to calculate the mean and the standard deviation of an array of floating-point values in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

func main() {
    numbers := []float64{3.4, 1.8, 4.3, 5.0, 6.2}
            
    mean := CalculateMean(numbers)
    stddev := CalculateStandardDeviation(numbers, mean)

    fmt.Printf("Mean: %.2f\n", mean)
    fmt.Printf("Standard Deviation: %.2f\n", stddev)
}

func CalculateMean(data []float64) float64 {
	if len(data) == 0 {
		return 0.0 // Mean of an empty set is conventionally 0
	}

	sum := 0.0
	for _, value := range data {
		sum += value
	}
	return sum / float64(len(data))
}


func CalculateStandardDeviation(data []float64, mean float64) float64 {
	n := float64(len(data))
	if n < 2 { // Standard deviation for n=0 or n=1 is not typically meaningful
		return 0.0
	}

	sumOfSquaredDifferences := 0.0

	for _, value := range data {
		diff := value - mean
		sumOfSquaredDifferences += diff * diff
	}

	// Calculate variance (sample variance: divide by N-1)
	variance := sumOfSquaredDifferences / (n - 1)

	// Standard deviation is the square root of the variance
	return math.Sqrt(variance)
}



/*
run:

Mean: 4.14
Standard Deviation: 1.66

*/

 



answered Jun 29, 2025 by avibootz
...