fix: probabilites not summing to 1
This commit is contained in:
@@ -7,7 +7,7 @@ import (
|
||||
"tz-snipe/internal/geodata"
|
||||
)
|
||||
|
||||
func getStatsForTZs(tzs []string) ([]Prediction, error) {
|
||||
func GetStatsForTZs(tzs []string) ([]Prediction, error) {
|
||||
// assumes tzs at this stage are uniq
|
||||
// 1. get geodata
|
||||
var predictions []Prediction
|
||||
@@ -25,13 +25,15 @@ func getStatsForTZs(tzs []string) ([]Prediction, error) {
|
||||
// but append handles init in case of slice
|
||||
// while maps are more strict
|
||||
// so here I need a map
|
||||
seenCountry := make(map[string]int)
|
||||
seenCountry := make(map[string]struct{})
|
||||
// another go quirk: structs take up 0 space
|
||||
// hence above
|
||||
var totalPop int64
|
||||
for _, countries := range tzMap {
|
||||
for _, country := range countries {
|
||||
for _, curTz := range tzs {
|
||||
for _, country := range tzMap[curTz] {
|
||||
if _, exists := seenCountry[country.Name]; !exists {
|
||||
totalPop += country.Population
|
||||
seenCountry[country.Name] = 1
|
||||
seenCountry[country.Name] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package core
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGetStatsForTZs(t *testing.T) {
|
||||
preds, err := getStatsForTZs([]string{"+0100", "+0000"})
|
||||
preds, err := GetStatsForTZs([]string{"+0100", "+0000"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -12,3 +15,20 @@ func TestGetStatsForTZs(t *testing.T) {
|
||||
t.Fatalf("failed to get predictions")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPredSum(t *testing.T) {
|
||||
preds, err := GetStatsForTZs([]string{"+0100"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// sum must be 1
|
||||
sum := 0.0
|
||||
for _, pred := range preds {
|
||||
sum += pred.Probability
|
||||
}
|
||||
|
||||
if math.Abs(sum-1) > 1e-6 {
|
||||
t.Fatalf("Probabilities did not sum to 1. Got %.4f instead", sum)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user