poly

mdhelper.fit.polynomial.poly(x: ndarray, *args: float) ndarray[source]

General polynomial model.

\[y=\sum_{k=0}^np_kx^k\]
Parameters:
xnumpy.ndarray

One-dimensional array containing \(x\)-values.

*argsfloat

Fitting parameters for each \(x^k\) term, starting with the \(x^0\) term. The number of positional arguments, \(n+1\), determines the order \(n\) of the polynomial model.

Returns:
fitnumpy.ndarray

Fitted \(y\)-values.

Examples

Generate \(x\)- and \(y\)-values (with error), and then use scipy.optimize.curve_fit() to fit coefficients for a third-order polynomial.

>>> from scipy import optimize
>>> rng = np.random.default_rng()
>>> x = np.arange(-2, 3)
>>> err = (2 * rng.random(x.shape) - 1) / 10
>>> y = x ** 2+2 * x+1+err
>>> pk, _ = optimize.curve_fit(lambda x, p0, p1, p2: poly(x, p0, p1, p2), x, y)
>>> pk
array([0.98225396, 2.0243695 , 1.01370609])

Evaluate the fitted \(y\)-values using the coefficients.

>>> poly(x, *pk)
array([ 0.9883393 , -0.02840946,  0.98225396,  4.02032955,  9.08581731])