correlation.go 742 B

123456789101112131415161718192021222324252627282930313233
  1. package stats
  2. import "math"
  3. // Correlation describes the degree of relationship between two sets of data
  4. func Correlation(data1, data2 Float64Data) (float64, error) {
  5. l1 := data1.Len()
  6. l2 := data2.Len()
  7. if l1 == 0 || l2 == 0 {
  8. return math.NaN(), EmptyInput
  9. }
  10. if l1 != l2 {
  11. return math.NaN(), SizeErr
  12. }
  13. sdev1, _ := StandardDeviationPopulation(data1)
  14. sdev2, _ := StandardDeviationPopulation(data2)
  15. if sdev1 == 0 || sdev2 == 0 {
  16. return 0, nil
  17. }
  18. covp, _ := CovariancePopulation(data1, data2)
  19. return covp / (sdev1 * sdev2), nil
  20. }
  21. // Pearson calculates the Pearson product-moment correlation coefficient between two variables.
  22. func Pearson(data1, data2 Float64Data) (float64, error) {
  23. return Correlation(data1, data2)
  24. }