normalize_test.go 731 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package format
  2. import (
  3. "math"
  4. "testing"
  5. )
  6. func TestNormalize(t *testing.T) {
  7. type testCase struct {
  8. input []float32
  9. }
  10. testCases := []testCase{
  11. {input: []float32{1}},
  12. {input: []float32{0, 1, 2, 3}},
  13. {input: []float32{0.1, 0.2, 0.3}},
  14. {input: []float32{-0.1, 0.2, 0.3, -0.4}},
  15. {input: []float32{0, 0, 0}},
  16. }
  17. assertNorm := func(vec []float32) (res bool) {
  18. sum := 0.0
  19. for _, v := range vec {
  20. sum += float64(v * v)
  21. }
  22. if math.Abs(sum-1) > 1e-6 {
  23. return sum == 0
  24. } else {
  25. return true
  26. }
  27. }
  28. for _, tc := range testCases {
  29. t.Run("", func(t *testing.T) {
  30. normalized := Normalize(tc.input)
  31. if !assertNorm(normalized) {
  32. t.Errorf("Vector %v is not normalized", tc.input)
  33. }
  34. })
  35. }
  36. }