PYTHON
Least square fit of a straight line from given points| Python
Introduction
In data analysis and curve fitting, one common task is to find the best-fitting line through a set of data points. This process is essential for understanding trends, making predictions, and extracting useful information from data. One popular method for fitting a straight line to data points is the least squares method. In this blog post, we'll explore the concept of least squares fitting of a straight line to given data points and provide a Python implementation to demonstrate the process.
Understanding Least Squares Fitting:
The least squares fitting aims to minimize the sum of the squares of the vertical deviations between the observed data points and the corresponding points on the fitted line. For a straight line given by the equation y=mx+c, the parameters m (slope) and c (intercept) are determined such that the sum of the squares of the vertical deviations is minimized.
Code
def least_squares_fit(x, y):
n = len(x)
sigmax = sum(x)
sigmay = sum(y)
sigmaxy = sum(x[i] * y[i] for i in range(n))
sigmaxx = sum(x[i] ** 2 for i in range(n))
m = (n * sigmaxy - sigmax * sigmay) / (n * sigmaxx - sigmax ** 2)
c = (sigmay - m * sigmax) / n
return m, c
# Input: Number of data points
n = int(input("Enter the total number of data points: "))
x = []
y = []
# Input: Data points
for i in range(1, n + 1):
print("Enter x%d, y%d:" % (i, i))
xp, yp = map(float, input().split())
x.append(xp)
y.append(yp)
# Calculate the slope and intercept of the best-fitting line
slope, intercept = least_squares_fit(x, y)
print("The best fitting line is y = %fx + %f" % (slope, intercept))
Output
Enter the total number of data points: 5
Enter x1, y1: 1 2
Enter x2, y2: 2 3
Enter x3, y3: 3 4
Enter x4, y4: 4 5
Enter x5, y5: 5 6
The best fitting line is y = 1.000000x + 1.000000
Explanation
1. We define a function least_squares_fit to calculate the slope and intercept of the best-fitting line using the least squares method.
2. We prompt the user to input the total number of data points and the coordinates of each data point.
3. The function least_squares_fit computes the slope and intercept using the provided data points.
4. Finally, we print the equation of the best-fitting line.
Conclusion
Least squares fitting is a powerful technique for finding the best-fitting line through a set of data points. In this blog post, we've discussed the theory behind least squares fitting and provided a Python implementation to perform this task. This method is widely used in various fields, including statistics, engineering, and data analysis, to extract meaningful insights from data and make accurate predictions.
Post a Comment
0 Comments