polyval method

Float64List polyval(
  1. Float64List x
)

Evaluates the coefficients stored by the most recent polyfit call.

If the stored coefficients are scaled-domain coefficients, the native context's saved scaling is used automatically.

Implementation

Float64List polyval(Float64List x) {
  final coeffs = _coeffs;
  final mode = _coeffMode;
  if (coeffs == null || mode == null) {
    throw StateError(
      'No fitted coefficients available. Call polyfit() first.',
    );
  }

  final n = x.length;
  ffi.Pointer<ffi.Double> xPtr = ffi.nullptr;
  ffi.Pointer<ffi.Double> coeffPtr = ffi.nullptr;
  ffi.Pointer<ffi.Double> outPtr = ffi.nullptr;

  try {
    xPtr = calloc<ffi.Double>(n);
    coeffPtr = calloc<ffi.Double>(deg + 1);
    outPtr = calloc<ffi.Double>(n);

    xPtr.asTypedList(n).setAll(0, x);
    coeffPtr.asTypedList(deg + 1).setAll(0, coeffs);

    final rc = mode == CoeffMode.scaled
        ? yl_polyfit_ctx_eval_scaled_f64(res.ctx, xPtr, n, coeffPtr, outPtr)
        : yl_polyfit_ctx_eval_xdomain_f64(res.ctx, xPtr, n, coeffPtr, outPtr);

    if (rc != 0) {
      throw StateError('polyval failed with code $rc');
    }

    return Float64List.fromList(outPtr.asTypedList(n));
  } finally {
    if (xPtr != ffi.nullptr) calloc.free(xPtr);
    if (coeffPtr != ffi.nullptr) calloc.free(coeffPtr);
    if (outPtr != ffi.nullptr) calloc.free(outPtr);
  }
}