To perform basic statistical analysis like calculating standard deviation and variance in Go, you can use the math
package. Here's an example that demonstrates how to do it:
package main
import (
"fmt"
"math"
)
func main() {
data := []float64{2.5, 3.5, 4.0, 5.5, 6.0}
// Calculate the mean
mean := calculateMean(data)
// Calculate the variance
variance := calculateVariance(data, mean)
// Calculate the standard deviation
standardDeviation := math.Sqrt(variance)
fmt.Printf("Mean: %.2f\n", mean)
fmt.Printf("Variance: %.2f\n", variance)
fmt.Printf("Standard Deviation: %.2f\n", standardDeviation)
}
func calculateMean(data []float64) float64 {
sum := 0.0
for _, value := range data {
sum += value
}
return sum / float64(len(data))
}
func calculateVariance(data []float64, mean float64) float64 {
sumOfSquares := 0.0
for _, value := range data {
sumOfSquares += math.Pow(value-mean, 2)
}
return sumOfSquares / float64(len(data))
}
In this example, we have a slice of data [2.5, 3.5, 4.0, 5.5, 6.0]
. We calculate the mean by summing up all the values and dividing it by the number of data points. Then, we calculate the variance by summing up the squared differences between each value and the mean, and dividing it by the number of data points. Finally, we calculate the standard deviation by taking the square root of the variance. The calculated mean, variance, and standard deviation are then printed to the console.
Please note that this example calculates the population variance and population standard deviation. If you want to calculate the sample variance and sample standard deviation, you'll need to adjust the divisor (len(data) - 1
) in the calculateVariance
function.