tTest function

(double, double) tTest(
  1. List<double> a,
  2. List<double> b
)

Performs a two-sample t-test.

Returns the t-statistic and p-value (two-tailed).

Implementation

(double tStatistic, double pValue) tTest(List<double> a, List<double> b) {
  final n1 = a.length;
  final n2 = b.length;

  if (n1 < 2 || n2 < 2) {
    throw ArgumentError('Each sample must have at least 2 observations');
  }

  // Calculate means
  double sum1 = 0, sum2 = 0;
  for (final x in a) {
    sum1 += x;
  }
  for (final x in b) {
    sum2 += x;
  }
  final mean1 = sum1 / n1;
  final mean2 = sum2 / n2;

  // Calculate variances
  double var1 = 0, var2 = 0;
  for (final x in a) {
    var1 += (x - mean1) * (x - mean1);
  }
  for (final x in b) {
    var2 += (x - mean2) * (x - mean2);
  }
  var1 /= (n1 - 1);
  var2 /= (n2 - 1);

  // Calculate t-statistic
  final se = math.sqrt(var1 / n1 + var2 / n2);
  if (se == 0) {
    return (double.infinity, 0);
  }

  final t = (mean1 - mean2) / se;

  // Approximate p-value using normal distribution for large df
  // For more accurate results, use Student's t-distribution
  // Note: Welch-Satterthwaite degrees of freedom could be computed as:
  // df = ((v1 + v2)^2) / ((v1^2)/(n1-1) + (v2^2)/(n2-1))
  // where v1 = var1/n1 and v2 = var2/n2, but we use normal approximation here.
  final pValue = 2 * (1 - _normalCdf(t.abs()));

  return (t, pValue);
}