correlation function

double correlation(
  1. List<double> x,
  2. List<double> y
)

Computes the Pearson correlation coefficient between two series.

Returns a value between -1 and 1, where:

  • 1 indicates perfect positive correlation
  • -1 indicates perfect negative correlation
  • 0 indicates no linear correlation

Implementation

double correlation(List<double> x, List<double> y) {
  if (x.length != y.length) {
    throw ArgumentError('x and y must have the same length');
  }
  if (x.length < 2) {
    throw ArgumentError('At least 2 points are required');
  }

  final n = x.length;

  // Calculate means
  double sumX = 0, sumY = 0;
  for (int i = 0; i < n; i++) {
    sumX += x[i];
    sumY += y[i];
  }
  final meanX = sumX / n;
  final meanY = sumY / n;

  // Calculate correlation components
  double ssXY = 0;
  double ssXX = 0;
  double ssYY = 0;

  for (int i = 0; i < n; i++) {
    final dx = x[i] - meanX;
    final dy = y[i] - meanY;
    ssXY += dx * dy;
    ssXX += dx * dx;
    ssYY += dy * dy;
  }

  if (ssXX == 0 || ssYY == 0) {
    return 0; // No variance in one or both variables
  }

  return ssXY / math.sqrt(ssXX * ssYY);
}