You can create a best fit line (also called a "least squares fitline" or "linear regression") to your data, using the function np.polyfit(xdata,ydata,degree). The first two arguments are arrays of the x-values and y-values to which you are fitting. The third argument is the degree of the polynomial used for fitting ("polyfit" = "polynomial fit"). We will use degree=1, which is a linear fit. Using degree=2, for example, would fit your data to a quadratic polynomial.
The np.polyfit function uses a "least squares fitting" technique similar to the method described in your lab manual.
In order to see what the form the output takes, consider the following example. In this case the input data will be an exactly straight line with the equation y=2x+1 and the fitline will fit exactly.
Evidently, the output of np.polyfit is an array, which looks a lot like the (slope, intercept) of the linear input. And indeed, you can check with the documentation that the output of this function is an array of the polynomial coefficients for the best fit polynomial, ordered from highest power to lowest power.
Now apply this technique to a noisy data set. Here we find and print the slope and intercept of the best fit line. In this case we round the values to three decimal places, due to the number of significant figures in our data.
Finally, we can visualize the fitline by plotting the smooth fitline along with our data.
No comments:
Post a Comment