Handle NaN values in weight validation function (#7)

NaN values can pass the validation since NaN values don't work
with float arithmetic and comparisons are always true. Now validation
function has check for NaN values.
This commit is contained in:
Alex Vanin 2019-08-01 12:16:03 +03:00 committed by GitHub
parent aa230933d1
commit f52ea8fb21
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 5 additions and 1 deletions

3
hrw.go
View file

@ -5,6 +5,7 @@ package hrw
import ( import (
"encoding/binary" "encoding/binary"
"errors" "errors"
"math"
"reflect" "reflect"
"sort" "sort"
@ -293,7 +294,7 @@ func prepareRule(slice interface{}) []uint64 {
// ValidateWeights checks if weights are normalized between 0.0 and 1.0 // ValidateWeights checks if weights are normalized between 0.0 and 1.0
func ValidateWeights(weights []float64) error { func ValidateWeights(weights []float64) error {
for i := range weights { for i := range weights {
if weights[i] > NormalizedMaxWeight || weights[i] < NormalizedMinWeight { if math.IsNaN(weights[i]) || weights[i] > NormalizedMaxWeight || weights[i] < NormalizedMinWeight {
return errors.New("weights are not normalized") return errors.New("weights are not normalized")
} }
} }

View file

@ -76,6 +76,9 @@ func TestValidateWeights(t *testing.T) {
weights := []float64{10, 10, 10, 2, 2, 2} weights := []float64{10, 10, 10, 2, 2, 2}
err := ValidateWeights(weights) err := ValidateWeights(weights)
require.Error(t, err) require.Error(t, err)
weights = []float64{math.NaN(), 1, 1, 0.2, 0.2, 0.2}
err = ValidateWeights(weights)
require.Error(t, err)
weights = []float64{1, 1, 1, 0.2, 0.2, 0.2} weights = []float64{1, 1, 1, 0.2, 0.2, 0.2}
err = ValidateWeights(weights) err = ValidateWeights(weights)
require.NoError(t, err) require.NoError(t, err)