Skip to content

Instantly share code, notes, and snippets.

@clungzta
Last active April 4, 2017 02:26
Show Gist options
  • Save clungzta/46c55c6fcf9da3d08f2f17004db127ef to your computer and use it in GitHub Desktop.
Save clungzta/46c55c6fcf9da3d08f2f17004db127ef to your computer and use it in GitHub Desktop.
Playing around with generating 1D polynomials using numpy
#For full reference, see http://docs.scipy.org/doc/numpy-1.10.1/reference/routines.polynomials.poly1d.html
def generate_poly(points, n):
'''
Generates an n degree polynomial from 2d array of discrete Points.
parameter points is a 2D numpy array: e.g. np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
'''
return np.poly1d(np.polyfit(points[:,0], points[:,1], n))
points = np.array([(1050, 1.0), (900, 0.775), (800, 0.5)])
poly_from_points = generate_poly(points, 3)
new_x_values = [1,2,3,4,5] #...
#Extrapolation / Interpolation
#Generate an array of y values for this polynomial; each value corresponds to its respective new_x_value
poly_from_roots_arr = np.polyval(poly_from_points, new_x_values)
############################################################################
'''
Generate a polynomial from array of coefficients
Parameter in poly1d is a list of polynomal roots
polynomial can be shifted up or down by "vertical_shift"
'''
x_values = [1,2,3,4,5] #...
vertical_shift = 0
poly_from_roots = np.poly1d([-1,0,1])
#Generate an array of y values for this polynomial; each value corresponds to its respective x_value
poly_from_roots_arr = np.polyval(poly_from_roots, x_values) + vertical_shift
############################################################################
'''
Generate a polynomial from list of coefficents, in decresing powers
'''
x_values = [1,2,3,4,5] #...
#e.g. 2x^2 + 1*x + 0
poly_from_coefficents = np.poly1d(c_or_r=[2,1,0], r=False)
#Generate an array of y values for this polynomial; each value corresponds to its respective x_value
poly_from_coefficents_arr = np.polyval(poly_from_coefficents, x_values)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment