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")

Saturday, August 11, 2018

Monte Carlo Crude Integration (User Defined Function)

Monte_clarlo_integration
% _________________________________________________________________________
% Monte Carlo crude integration
% By Mahesha MG, MIT
% Date: 11/08/2018
% _________________________________INPUT___________________________________
clc;
clear;
f=input('Enter a valid MATLAB expression in x : ','s');
a=input('Enter lower limit: ');
b=input('Enter upper limit: ');
n=input('Enter sampling number: ');
x=a+(b-a)*rand(1,n);
s=sum(eval(f));
result=(b-a)*s/n
% ______________________________SAMPLE OUTPUT______________________________
% Enter a valid MATLAB expression in x : x.^2+x
% Enter lower limit: 2
% Enter upper limit: 5
% Enter sampling number: 10000
%
% result =
%
%    49.3144
% _________________________________________________________________________