Hi, I'm Ataias Reis

Programmer, made in Brazil, Alma mater University of Brasilia

30 days of code in Go: Day 17 - Standard Deviation

Hi there! Today’s challenge was to compute standard deviation of an array of data given the formula $$\sigma = \sqrt{\frac{\sum_{i=0}^{N-1} (x_i - \mu)^2}{N}},$$ where $$\mu = \frac{\sum_{i=0}^{N-1} x_i}{N}.$$

The first input to the program is N and then N integers are fed to the program in sequence. My solution is given below.

package main

import (
 "fmt"
 "math"
)

func mean(a []int) float64 {
 n := float64(len(a))
 sum := 0.0
 for i := 0; i < len(a); i++ {
  sum += float64(a[i])
 }
 return sum / n
}

func sigma(a []int) float64 {
 mu := mean(a)
 sum := 0.0
 n := float64(len(a))
 for i := 0; i < len(a); i++ {
  x := float64(a[i])
  sum += (x - mu) * (x - mu)
 }
 sigma := math.Sqrt(sum / n)
 return sigma
}

func main() {

 N := 0
 fmt.Scanf("%d", &N)

 // allocate memory
 X := make([]int, N)

 // read numbers from stdin
 for i := 0; i < N; i++ {
  fmt.Scanf("%d", &X[i])
 }

 y := sigma(X)
 fmt.Printf("%.1f\n", y)
}

The problem I had this time was with HackerRank. On my computer I had a result, but their system was saying it had a different result. After that I ran it again on HackerRank using the option custom input, but with the same input that gave me a bad answer error, but this time the answer was ok. Bugs appear everywhere, right? I will submit it with another language, still thinking about it. I wrote something to them, hopefully they will fix this bug.

That’s all for today! Thanks for reading!

Tags
comments powered by Disqus