Example: Find the least squares approximation to Exp[2x] in (Subscript[P, 2]) on the interval [0,1]

p1=1;
p2=Sqrt[12](x-1/2);
p3=Sqrt[180](x^2-x+1/6); (* ON basis for (Subscript[P, 2]) *)

c1=Integrate[Exp[2x] p1,{x,0,1}]
c2=Integrate[Exp[2x] p2,{x,0,1}]
c3=Integrate[Exp[2x] p3,{x,0,1}] (* inner products of f with each basis polynomial *)

Plot[{Exp[2x],c1 p1+c2 p2+c3 p3},{x,0,1}] (* plot of f and its (Subscript[P, 2]) approximation *)

Example: Find the least squares approximation to Sin[x] in (Subscript[P, 1]) on the interval [-1,1]

p1=1/Sqrt[2];
p2=Sqrt[3/2]x; (* ON basis for (Subscript[P, 1]) *)

c1=Integrate[Sin[x]p1,{x,-1,1}]
c2=Integrate[Sin[x]p2,{x,-1,1}] (* inner products of f with each basis polynomial *)

Plot[{Sin[x],c1 p1+c2 p2},{x,-1,1}] (* plot of f and its (Subscript[P, 1]) approximation *)