Polynomial<T>.lagrange constructor

Polynomial<T>.lagrange(
  1. DataType<T> dataType, {
  2. required Vector<T> xs,
  3. required Vector<T> ys,
  4. PolynomialFormat? format,
})

Builds a Lagrange Polynomial through the unique sample points xs and ys. Related to lagrangeInterpolation.

See https://en.wikipedia.org/wiki/Lagrange_polynomial.

Implementation

factory Polynomial.lagrange(
  DataType<T> dataType, {
  required Vector<T> xs,
  required Vector<T> ys,
  PolynomialFormat? format,
}) {
  checkPoints<T>(dataType, xs: xs, ys: ys, min: 1, unique: true);
  final sub = dataType.field.sub, div = dataType.field.div;
  final result = Polynomial<T>(dataType);
  for (var i = 0; i < xs.count; i++) {
    final roots = <T>[];
    var scalar = ys.getUnchecked(i);
    for (var j = 0; j < xs.count; j++) {
      if (j != i) {
        scalar = div(scalar, sub(xs.getUnchecked(i), xs.getUnchecked(j)));
        roots.add(xs.getUnchecked(j));
      }
    }
    result
        .addEq(Polynomial<T>.fromRoots(dataType, roots).mulScalarEq(scalar));
  }
  return result;
}