Created
August 1, 2023 17:23
-
-
Save mcpar-land/d8d4d39c52cb03afcf8d7ab38824beac to your computer and use it in GitHub Desktop.
go running average
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
) | |
func main() { | |
src := []float64{} | |
for i := 0; i < 100; i++ { | |
src = append(src, rand.Float64()*1000) | |
} | |
fmt.Println(src) | |
var avg1 float64 = 0.0 | |
for _, v := range src { | |
avg1 += v | |
} | |
avg1 /= float64(len(src)) | |
fmt.Println("Method 1 average: ", avg1) | |
var avg2 float64 = 0.0 | |
for i, v := range src { | |
avg2 = ((avg2 * float64(i)) + v) / float64(i+1) | |
} | |
fmt.Println("Method 2 average: ", avg2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment