cosine.go 733 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package cosine
  2. import (
  3. "errors"
  4. "math"
  5. )
  6. // https://github.com/gaspiman/cosine_similarity/blob/master/cosine.go
  7. func Cosine(a []float64, b []float64) (cosine float64, err error) {
  8. count := 0
  9. length_a := len(a)
  10. length_b := len(b)
  11. if length_a > length_b {
  12. count = length_a
  13. } else {
  14. count = length_b
  15. }
  16. sumA := 0.0
  17. s1 := 0.0
  18. s2 := 0.0
  19. for k := 0; k < count; k++ {
  20. if k >= length_a {
  21. s2 += math.Pow(b[k], 2)
  22. continue
  23. }
  24. if k >= length_b {
  25. s1 += math.Pow(a[k], 2)
  26. continue
  27. }
  28. sumA += a[k] * b[k]
  29. s1 += math.Pow(a[k], 2)
  30. s2 += math.Pow(b[k], 2)
  31. }
  32. if s1 == 0 || s2 == 0 {
  33. return 0.0, errors.New("Vectors should not be null (all zeros)")
  34. }
  35. return sumA / (math.Sqrt(s1) * math.Sqrt(s2)), nil
  36. }