Sunday, September 8, 2024

Python Code for Linear Least Square Fit

1_Least Square fit.py
1_Least Square fit.py
import numpy as np
import matplotlib.pyplot as plt

# Example dataset
data = np.loadtxt('LeastSquare.txt')
x = data[:, 0]  # First column: independent variable
y = data[:, 1]  # Second column: dependent variable

# Perform linear least squares fit
slope, intercept = np.polyfit(x, y, 1)

# Generate line of best fit
y_fit = slope * x + intercept

# Print the results
print(f"Slope: %.2f" % slope)
print(f"Intercept: %.2f" % intercept)

# Plot data points and line of best fit
plt.scatter(x, y, label='Data Points')
plt.plot(x, y_fit, color='red', label='Best Fit Line')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show()

# Write result data to a text file
with open('LeastSquareResult.txt', 'w') as file:
    # Write the header
    file.write('x\ty\ty_fit\n')
    
    # Write the data
    for c1, c2, c3 in zip(x, y, y_fit):
        file.write(f'{c1}\t{c2}\t{c3}\n')

print("Data written to LeastSquareResult.txt")

No comments:

Post a Comment