covariance method
T
covariance()
Calculates covariance of x and y.
Throws ArgumentError when:
- The arguments have non-equal lengths.
- The arguments are empty.
Example
import 'package:calc/calc.dart';
void main() {
final x = [1,2,3];
final y = [4,3,2];
final result = SamplesXY<int>(x,y).covariance();
print('covariance: $result');
}
Implementation
T covariance() {
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 meanX = x.mean();
final meanY = y.mean();
final sum = meanX.toBuilder(copy: false);
final tmp0 = sum.toBuilder(copy: false);
final tmp1 = sum.toBuilder(copy: false);
for (var i = 0; i < n; i++) {
// x[i] - meanX
tmp0.setTensor(x[i]);
tmp0.sub(meanX);
// y[i] - meanY
tmp1.setTensor(y[i]);
tmp1.sub(meanY);
// (x[i] - meanX) * (y[i] - meanY)
tmp0.mul(tmp1.build(recycle: true));
if (i == 0) {
sum.setTensor(tmp0.build(recycle: true));
} else {
sum.add(tmp0.build(recycle: true));
}
}
sum.divScalar(n);
return sum.build() as T;
}