Basic Python Progamming Define a function polynomialfit xs y

Basic Python Progamming

Define a function polynomial_fit( xs, ys, degree ) that takes in two lists of numerical values (one representing x-coordinates and the other y-coordinates) and an integer representing degree (1 is linear, 2 is quadratic, 3 is cubic, etc.). The function returns a list containing y-coordinates from the calculated polynomial regression equation.

This function should:

Find constants for a polynomial regression equation of the inputted degree for the given xs and ys using the polyfit function.

Create a polynomial function by plugging the coefficients from the regression equation into poly1d.

Example Usage:
>>> xs = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> ys = [ 4, 7, 12, 16, 10, 10, 9, 15, 17, 19, 10, 8, 6, 5, 2, 1]
>>> polynomial_fit(xs, ys, 5)
array([ 3.34700722, 9.34791022, 11.36687307, 11.65538422,
11.59972613, 11.88190641, 12.64058903, 13.63202548,
14.39098595, 14.39169048, 13.20874018, 10.67804834,
7.05777169, 3.18924149, 0.65789474, 1.95420537])

Solution

import numpy as np
def polynomial_fit(xs, ys, degree):
     return(np.poly1d(np.polyfit(np.array(xs), np.array(ys), degree))(xs))

Basic Python Progamming Define a function polynomial_fit( xs, ys, degree ) that takes in two lists of numerical values (one representing x-coordinates and the o

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site