In (ℝ^3)

v1={1,0,2};
v2={2,5,-1};
v3={-2,1,1};

w={4,3,7}

dsquared=(w-a1*v1).(w-a1*v1)

Plot[dsquared,{a1,0,8}]

Minimize[dsquared,a1]

dsquared=(w-(a1*v1+a2*v2)).(w-(a1*v1+a2*v2))

Minimize[dsquared,{a1,a2,a3}]

dsquared=(w-(a1*v1+a2*v2+a3*v3)).(w-(a1*v1+a2*v2+a3*v3))

Minimize[dsquared,{a1,a2,a3}]

w.v1/v1.v1

w.v2/v2.v2

w.v3/v3.v3

18/5 v1+8/15v2+1/3v3

In (L^2)[-π,π]

Clear[f]

f[x_]=Piecewise[{{Pi^2/8(-2-2/Pi x),-Pi<x<-Pi/2},{Pi^2/8(2/Pi x),-Pi/2<x<Pi/2},{Pi^2/8(2-2/Pi x), Pi/2<x<Pi}}]

Plot[f[x],{x,-Pi,Pi},
Ticks->{Range[-Pi,Pi,Pi/2],Range[-Pi^2/8,Pi^2/8,Pi^2/8]}]

mse=Integrate[(f[x]-a1*Sin[x])^2,{x,-Pi,Pi}]

Plot[mse,{a1,-2,4}]

Minimize[mse,a1]

mse=Integrate[(f[x]-a1*Sin[x]-a2*Sin[2x]-a3*Sin[3x])^2,{x,-Pi,Pi}]

Minimize[mse,{a1,a2,a3}]

Manipulate[
e=NIntegrate[(f[x]-a1*Sin[x]-a2*Sin[2x]-a3*Sin[3x])^2,{x,-Pi,Pi}];
Show[Plot[{f[x],a1*Sin[x]+a2*Sin[2x]+a3*Sin[3x],(f[x]-a1*Sin[x]-a2*Sin[2x]-a3*Sin[3x])^2},{x,-Pi,Pi},PlotRange->{-1.5,1.5},ImageSize->Medium],Graphics[Text[StringForm["mean square error=``",PaddedForm[e,{5,5}]],{2,-1},BaseStyle->12]]],
{{a1,0},-2,2},
{{a2,0},-1,1},
{{a3,0},-1,1}]