Search code examples
pythonnumpyscipycalculussymbolic-integration

Python - Generate polynomial from turning point coordinates


Diagram

Using a list of coordinates of the turning points of a polynomial, I am trying to find a list of coefficients of the polynomial. The diagram above graphically shows what I'm trying to work out.

I have tried to use numpy.polyfit to generate a polynomial, however the polynomial given goes through these points wherever, rather than specifically at the turning points.

Does there exist a function which could do this?

If there is no such function an approach I am considdering is to integrate (x-turningX[0])(x-turningX[1])(x-turningX[n]) to find the polynomial but I am unsure how I would go about this in python.


Solution

  • You can create such a curve with scipy.interpolate.CubicHermiteSpline by giving it an array of zeros for the dydx parameter. For example, this code

    In [60]: import numpy as np
    
    In [61]: from scipy.interpolate import CubicHermiteSpline
    
    In [62]: x = np.array([1, 2.5, 4.5, 6, 7])  # x coordinates of turning points
    
    In [63]: y = np.array([1, 3, 2, 3.5, 2.5])  # y coordinates of turning points
    
    In [64]: p = CubicHermiteSpline(x=x, y=y, dydx=np.zeros_like(y))  # interpolator   
    
    In [65]: plot(x, y, 'o')
    Out[65]: [<matplotlib.lines.Line2D at 0xa2f1aef90>]
    
    In [66]: xx = np.linspace(0.9, 7.1, 1000)
    
    In [67]: plot(xx, p(xx))
    Out[67]: [<matplotlib.lines.Line2D at 0xa287fb9d0>]
    

    generates this plot: plot