How to implement basic statistical calculations (mean, median, mode) in Go?

To implement basic statistical calculations (mean, median, mode) in Go, you can use the built-in packages and write your own functions. Here's an example implementation:

  1. Mean Calculation:
func Mean(numbers []float64) float64 { sum := 0.0 for _, num := range numbers { sum += num } return sum / float64(len(numbers)) }
  1. Median Calculation:
func Median(numbers []float64) float64 { sort.Float64s(numbers) middle := len(numbers) / 2 if len(numbers)%2 == 0 { return (numbers[middle-1] + numbers[middle]) / 2 } return numbers[middle] }
  1. Mode Calculation:
func Mode(numbers []float64) []float64 { frequency := make(map[float64]int) for _, num := range numbers { frequency[num]++ } maxFrequency := 0 modes := []float64{} for num, count := range frequency { if count > maxFrequency { maxFrequency = count modes = []float64{num} } else if count == maxFrequency { modes = append(modes, num) } } return modes }

You can use these functions in your code as follows:

func main() { numbers := []float64{1, 2, 3, 3, 4, 5, 5, 5} mean := Mean(numbers) median := Median(numbers) modes := Mode(numbers) fmt.Println("Mean:", mean) fmt.Println("Median:", median) fmt.Println("Mode(s):", modes) }

This will calculate and print the mean, median, and mode(s) of the given numbers.