Curve fitting
AIM: To write code to fit a linear and cubic polynomial for the Cp dara.
THEORY:
Curve fitting is the process of constructing a curve pr mathematical function , that has the best fit to a series of data points, possibly subject to constraints.
To find the goodness of a fit there are four methods
1. The sum of squares due to errors(sse)
2. R square
3.Adjusted R square
4.Root mean squared error
How to make perfect fit:
In order to make perfect fit we must consider error estimates as well. Perfect fit means, the curve should fit the original curve without showing any errors in that degree of polynomial.
PERFECT FIT CAN BE ALWAYS BE A BEST FIT BUT BEST FIT CAN NOT BE A PERFECT FIT .
How to get the best fit:
For this we use rms method .We can change the order of polynomial to get the perfect fit and the best way is to split the data into two or more data and do the curve fit.
error=|y(i)-value of f(x)|=|y(i)-f(i))|
sse=`sum_(i=1)^n`error`(i)^2`
ssr=`sum_(i=1)^n`(Y(i)-f((x)))^2
sst=ssr+sse
r^2=ssr/sst
Code for linear curve :
clear all
close all
clc
%preparing the data
cp_data = load('data');
temperature = cp_data(:,1);
cp= cp_data(:,2);
% curve fit
co_effs1= polyfit(temperature,cp,1);
predicted_cp= polyval(co_effs1,temperature);
%compare my curve fit with the orginal data
plot(temperature,cp,'linewidth',3)
hold on
plot(temperature,predicted_cp,'linewidth',3,'color','r')
xlabel('temperature[K]')
ylabel('specific heat [KJ/Kmol-k]')
legend('original dataset','curvefit')
Now for cubic curve:
clear all
close all
clc
%preparing the data
cp_data = load('data');
temperature = cp_data(:,1);
cp= cp_data(:,2);
% curve fit
co_effs1= polyfit(temperature,cp,3);
predicted_cp= polyval(co_effs1,temperature);
%compare my curve fit with the orginal data
plot(temperature,cp,'linewidth',3)
hold on
plot(temperature,predicted_cp,'linewidth',3,'color','r')
xlabel('temperature[K]')
ylabel('specific heat [KJ/Kmol-k]')
legend('original dataset','curvefit')
But here we get the error in command error
To eliminate this we have to split by estimating errors
and code for this
clear all
close all
clc
insert_data=load('data');
temp=insert_data(:,1);
cp=insert_data(:,2);
a=1;
b=400;
hold on
plot(temp,cp)
for i=1:8
co_ef(i,:)=polyfit(temp(a:b),cp(a:b),2);
predicted_cp(i,:)=polyval(co_ef(i,:),temp(a:b));
predicted_cp1(a:b)=predicted_cp(i,:);
plot(temp(a:b),predicted_cp(i,:),'color','r')
hold on
a=b+1;
b=b+400;
end
ssr=0;
sse=0;
sum=0;
for j=1:length(cp)
sse=sse+(cp(j)-predicted_cp1(j))^2;
sum=sum+cp(j);
end
mean=sum/length(cp);
for j=1:length(cp);
ssr=ssr+(predicted_cp1(j)-mean)^2;
end
sst=ssr+sse;
r_square=ssr/sst;
fprintf('splitted curve:%f',r_square)
xlabel('temperature')
ylabel('specific heat')
legend('original','curvefit')
grid on
References:
https://projects.skill-lync.com/projects/Curve-Fitting-and-criterion-to-choose-best-fit-41860