1
votes

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.

1
What exactly do you mean by "the polynomial given goes through these points wherever"? Don't you want it to pass through the points? Please edit your code into your question as a minimal reproducible example and add an image of the output 'fitted' curve overlaid on the data provided to numpy.polyfit(). Also please provide the data used - so I could paste the code into a file, paste the data into another file (or included in the code) and run it without adding anything to see the same result you get.balmy
You could draw a bezier curve through your points as in Using matplotlib to “smoothen” a line with very few points. A normal polyfit can oscillate quite heavily. Only curves that are composed of multiple touching curves can have controlled behavior. A single polynomial can't accomplish mathematically what you're asking.JohanC
@JohanC thank you that is exactly the sort of thing I needed!damoys
@JohanC, of course a single polynomial can accomplish what is requested. With a high enough degree, a single polynomial can fit an elephant. :)Warren Weckesser
@damoys, do you really need a polynomial, or just any smooth curve through the turning points?Warren Weckesser

1 Answers

2
votes

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