correlation method
T
correlation()
Calculates correlation of x and y.
Throws ArgumentError when:
- The arguments have non-equal lengths.
- The arguments are empty.
- Either argument has zero variance (all elements are identical).
Example
import 'package:calc/calc.dart';
void main() {
final x = [1,2,3];
final y = [4,3,2];
final result = SamplesXY<int>(x, y).correlation();
print('correlation: $result');
}
Implementation
T correlation() {
final n = x.length;
if (n != y.length) {
throw ArgumentError(
'Arguments have different lengths: ${x.length} != ${y.length}');
}
if (n == 0) {
throw ArgumentError('Arguments are empty');
}
final xVariance = x.variance();
if (xVariance.elements.contains(0.0)) {
if (xVariance.isScalar) {
throw ArgumentError('Variance of `x` is zero');
}
throw ArgumentError('Variance of `x` has a zero element');
}
final yVariance = y.variance();
if (yVariance.elements.contains(0.0)) {
if (yVariance.isScalar) {
throw ArgumentError('Variance of `y` is zero');
}
throw ArgumentError('Variance of `y` has a zero element');
}
return covariance() / (xVariance * yVariance) as T;
}