Is there a Python function for finding a function for the fit curve of a set of points?
Question:
Say I have a set of points. I know about a lot of options for fitting a curve for those points, such as numpy.polyfit()
and scipy.fit_curve
.
How can I get a function for the fit curve? In other words, how can I get the y value for an x value based on those set of points?
Sorry for awkward wording, I don’t know how to phrase this.
Answers:
In numpy
, you can pass numpy.polyfit
to numpy.poly1d
which then returns a function that you can pass x-values to.
Example:
>>> import numpy as np
>>> points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
>>> x = points[:,0]
>>> y = points[:,1]
>>> a = np.polyfit(x, y, 3)
>>> f = np.poly1d(a)
>>> f(1)
1.0000000000000675
>>> f(3)
1.0000000000000284
>>> f(6)
-17.928571428571125
Say I have a set of points. I know about a lot of options for fitting a curve for those points, such as numpy.polyfit()
and scipy.fit_curve
.
How can I get a function for the fit curve? In other words, how can I get the y value for an x value based on those set of points?
Sorry for awkward wording, I don’t know how to phrase this.
In numpy
, you can pass numpy.polyfit
to numpy.poly1d
which then returns a function that you can pass x-values to.
Example:
>>> import numpy as np
>>> points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
>>> x = points[:,0]
>>> y = points[:,1]
>>> a = np.polyfit(x, y, 3)
>>> f = np.poly1d(a)
>>> f(1)
1.0000000000000675
>>> f(3)
1.0000000000000284
>>> f(6)
-17.928571428571125