Minstakvadratmetoden

Exempel från föreläsningen

Exempel 1

Remove["Global`*"]
xv={0,1,2,3,4};
y={1,2,3,4,6};
data=Transpose[{xv,y}];
nmax=Length[xv];
a=Transpose[{xv,Table[1,{i,1,nmax}]}];
p={k,m};
f={x,1}.p;
sol=Solve[Transpose[a].a.p==Transpose[a].y,p];
Print["f(x,p) = ",N[f/.sol[[1]]]]
pl=Plot[f/.sol[[1]],{x,xv[[1]],xv[[nmax]]}];
lp=ListPlot[data,PlotStyle->{Red,PointSize[Large]}];
Print["Jämför med Mathematicas funktion Fit: ",Fit[data,{1,x},x]]
Show[lp,pl]

Exempel 5

Remove["Global`*"]
xv={0,1,2,3,4};
y={3,2,3,4,8};
xv2=xv^2;
n=Length[xv];
a=Transpose[{xv2,xv,Table[1,{i,1,n}]}];
deg=2;
p=Reverse[Table[c[i],{i,0,deg}]];
f=Reverse[Table[x^(i),{i,0,deg}]].p;
data=Transpose[{xv,y}];
sol=Solve[Transpose[a].a.p==Transpose[a].y,p];
Print["f(x,p) = ",N[f/.sol[[1]]]]
Print["Jämför med Mathematicas funktion Fit: ",Fit[data,{1,x,x^2},x]]
pl=Plot[f/.sol[[1]],{x,xv[[1]],xv[[n]]}];
lp=ListPlot[data,PlotStyle->{Red,PointSize[Large]}];
Show[pl,lp]

Exempel 6

Remove["Global`*"]
xv={0,1,2,3,4};
yv={1,2,3,5,10};
y=Log[yv];
n=Length[xv];
a=Transpose[{xv,Table[1,{i,1,n}]}];
deg=1;
p=Reverse[Table[c[i],{i,0,deg}]];
f=Reverse[Table[x^(i),{i,0,deg}]].p;
data=Transpose[{xv,y}];
sol=Solve[Transpose[a].a.p==Transpose[a].y,p];
Print["f(x,p) = ",N[f/.sol[[1]]]]
Print["Jämför med Mathematicas funktion Fit: ",Fit[data,{1,x},x]]
pl=Plot[f/.sol[[1]],{x,xv[[1]],xv[[n]]},PlotLabel->"ln y = ln c + kx"];
lp=ListPlot[data,PlotStyle->{Red,PointSize[Large]}];
Show[pl,lp]
Print["c = ",c=N[Exp[c[0]]/.sol[[1]]]]
Print["k = ",k=N[c[1]/.sol[[1]]]]
data2=Transpose[{xv,yv}];
Print["Jämför med Mathematicas funktion FindFit: ",fit=FindFit[data2,cc*Exp[kk*x],{cc,kk},x]]
pl=Plot[{c*Exp[k*x],(cc*Exp[kk*x]/.fit)},{x,xv[[1]],xv[[n]]},
PlotRange->{0,11},
PlotLabel->"y = c (e^kx)",
PlotLegends->Placed[{"MKM","Mathematicas FindFit"},{0.3,0.9}]
];
lp=ListPlot[data2,PlotStyle->{Red,PointSize[Large]}];
Show[pl,lp]

Exempel 7

Remove["Global`*"]
y[x_]=0.3Cos[4x]+Exp[x];
n=3; (* Max grad på p *)
For[k=1,k<=n,k++,
p=Table[c[i],{i,0,k}];
f[x_]=Table[x^i,{i,0,k}].p;
s=Integrate[(f[x]-y[x])^2,{x,0,1}];
sol=Solve[D[s,{p}]==0,p];
Plot[{y[x],f[x]/.sol[[1]]},{x,0,1},
PlotLegends->{"y(x)","f(x,p)"},
Epilog->{Text["n = ",{0.46,2}],Text[k,{0.5,2}]}]//Print
]