Golang Program to Calculate Standard Deviation


In this tutorial, we will write a go language code to calculate the standard deviation. The standard deviation is a statistic that expresses how much variance or dispersion there is in a group of numbers. It is calculated as the square root of the mean.

Find the Standard Deviation Using External Functions

In this example, we will write a go language program to calculate the standard deviation using user-defined functions.

Algorithm to the Above Program

Step 1 − Import the fmt, math, and start.

Step 2 − Create the standardDeviation() function. This function uses a for loop to intend over the array and update the sum variable.

Step 3 − Use a new for loop to update the sd variable by taking the square of each array value after subtracting it from the mean.

Step 4 − Take the square root of the above value obtained and return it from the function.

Step 5 − Start the main() function.

Step 6 − Initialize an array of integers, assign values to it and print the array on the screen.

Step 7 − Now, call the standardDeviation() function by passing the array of integers as argument to the function and store the result in a variable

Step 8 − Next, print the result on the screen using fmt.Println() function.

Example

package main
import (
   "fmt"
   "math"
)
func standardDeviation(num [10]float64) float64 {
   var sum, mean, sd float64
   for i := 1; i <= 10; i++ {
      num[i-1] = float64(i) + 123
      sum += num[i-1]
   }
   mean = sum / 10
   fmt.Println("The mean of above array is:", mean)
   for j := 0; j < 10; j++ {
      sd += math.Pow(num[j]-mean, 2)
   }
   sd = math.Sqrt(sd / 10)
   return sd
}
func main() {
   num := [10]float64{1, 3, 5, 7, 9, 11, 2, 4, 6, 8}
   fmt.Println("The given array is:", num)
   sd := standardDeviation(num)
   fmt.Println("The Standard Deviation of the above array is:", sd)
}

Output

The given array is: [1 3 5 7 9 11 2 4 6 8]
The mean of above array is: 128.5
The Standard Deviation of the above array is: 2.8722813232690143

Conclusion

We have successfully compiled and executed a go language code to calculate the standard deviation along with examples. In the first code we have used implemented the result by using a user defined function.

Updated on: 28-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements