Fitting a linear function a(x-b) to Sin(x) over the critical interval (0,Pi/2)

Andy Long

We want to find the line that gives the best fit over the whole interval, which we determine by minimizing the squared differences between Sin(x) and a(x-b) over the entire interval (i.e., by minimizing an integral):

Clear[a,b]
Integrate[(a(x-b)-Sin[x])^2,{x,0,Pi/2}]
errorOverInterval[a_,b_]:=Integrate[(a(x-b)-Sin[x])^2,{x,0,Pi/2}]

So we compute some partial derivatives:

solna=D[errorOverInterval[a,b],a]
solnb=Simplify[D[errorOverInterval[a,b],b]]

Then solve for the combo of (a,b) that make this minimal:

sols=N[Solve[solna==0 &&solnb==0,{a,b}]]

There are two solutions, but it’s the second which is the best fitting (the first is spurious):

errorOverInterval[a/.sols[[2]][[1]],b/.sols[[2]][[2]]]
a=a/.sols[[2]][[1]]
b=b/.sols[[2]][[2]]

Let’s take a look at our results, and the error:

p1=Plot[{a(x-b),Sin[x]},{x,0,Pi/2},PlotLabel->errorOverInterval[a,b]];
p2=Plot[{a(x-b)-Sin[x]},{x,0,Pi/2},PlotLabel->errorOverInterval[a,b]];
Show[p1,p2,PlotRange->All]

What are the x-values for the “knots” (intersections between the two curves):

solns=Solve[a(x-b)==Sin[x],x,Reals]
xs=x/.solns
(* These two are the ones that are visible on this interval: *)
{xs[[2]],xs[[3]]}
p1=ListPlot[{{xs[[2]],0},{xs[[3]],0}},PlotMarkers->{}];
Show[p2,p1,PlotRange->All]

ShowFit[a_,b_]:=Plot[{a(x-b),Sin[x]},{x,0,Pi/2},PlotLabel->errorOverInterval[a,b]]
p1=ShowFit[a,b];
p2=ListPlot[{{xs[[2]],Sin[xs[[2]]]},{xs[[3]],Sin[xs[[3]]]}}];
Show[p1,p2]

p1=Plot3D[-2 a+2 a b+(1/24) π (6+(a^2) (12 (b^2)-6 b π+(π^2))),{a,-2,2},{b,-2,2}];
p2=ListPointPlot3D[{{a,b,errorOverInterval[a,b]}},PlotStyle->Directive[Black,PointSize->Large]];
Show[p1,p2]