linearInterpolation function

List<double> linearInterpolation(
  1. List<double> x,
  2. List<double> xp,
  3. List<double> yp
)

Implementation

List<double> linearInterpolation(
  List<double> x,
  List<double> xp,
  List<double> yp,
) {
  if (xp.length != yp.length) throw ArgumentError('xp/yp length mismatch');
  if (xp.isEmpty) {
    return x.isEmpty ? [] : throw ArgumentError('Empty reference points');
  }

  return x.map((xi) {
    if (xi <= xp.first) return yp.first;
    if (xi >= xp.last) return yp.last;

    int left = 0, right = xp.length - 1;
    while (left < right - 1) {
      final mid = (left + right) ~/ 2;
      if (xi < xp[mid]) {
        right = mid;
      } else {
        left = mid;
      }
    }

    final slope = (yp[right] - yp[left]) / (xp[right] - xp[left]);
    return yp[left] + slope * (xi - xp[left]);
  }).toList();
}