Find the best polynomial approximation of the piecewise function Find the best approximation of the function
$$ f(x)= \begin{cases}
1 - x \quad\text{ for  } 0 \le x \le 1 \\
1 + x \quad\text{ for  } -1 \le x \le 0 \\
\end{cases}$$
in the interval $[-1,~ 1]$ by a polynomial $p(x)$ of degree $\le 4$, meaning that the integral 
$$\int_{-1}^{1} (|f(x) - p(x)|)^2\,{\rm d}x $$ is minimal possible.
We know that the best approximation is unque and coinced with the orthogonal projection. The minimal distance is equal to to length of orthogonal projection of $x$ into ${\rm ort}_{U}x$.
 A: Given a function $f\in L^2[-1,1]$, the polynomial of degree $d$ (in your case $d=4$) minimizing that quantity is
$\sum_{k=0}^d \alpha_k P_k(x)$
Where:


*

*$P_k(x)=\frac{1}{2^kk!}\frac{d^k}{dx^k}[(x^2-1)^k]$, also known as the k-th Legendre polynomial. It's a suitable multiple of the k-th derivative of $(x^2-1)^k$, and it has degree exactly $k$. Legendre polynomials are a complete orthogonal system fro $L^2[-1,1]$; they are not orthonormal, since $\|P_k\|_2=\sqrt{\frac{2}{2k+1}}$.

*$\alpha_k=\frac{2k+1}{2}\int_{-1}^1f(x)P_k(x)dx$
Wikipedia provides $P_k(x)$ for $k=0,\ldots,10$, you need the first 5 of them:
$$P_0(x)=1\\P_1(x)=x\\P_2(x)=\frac{3x^2-1}{2}\\P_3(x)=\frac{5x^3-3x}{2}\\P_4(x)=\frac{35x^4-30x^2+3}{8}$$
The rest is a calculation.
A: $\newcommand{\Er}{{\rm Error}}$
Define the problem and solve the differential calculus:
$$\begin{align}
%
\Er(A, B, C, D, E)
%
   &= \int_{-1}^{1} (Ax^4 + Bx^3 + Cx^2 + Dx + E - f(x))^2 ~dx
%
\\ \\ &= \int_{-1}^{0} (Ax^4 + Bx^3 + Cx^2 + Dx + E - 1 - x)^2 ~dx \\
   \\ &+  \int_{0}^{1}  (Ax^4 + Bx^3 + Cx^2 + Dx + E - 1 + x)^2 ~dx 
%
\\ \\ &=  \frac{2\,{A}^{2}}{9}  +  \frac{2\,{B}^{2}}{7}  +  \frac{2\,{C}^{2}}{5}  +  \frac{2\,{D}^{2}}{3}  +  \frac{2\,{E}^{2}}{1}
   \\ &-  \frac{2\,A}{15}  -  \frac{C}{3}  -  2\,E
   \\ &+  \frac{4\,A\,E}{5}  +  \frac{4\,C\,E}{3}  +  \frac{4\,B\,D}{5}  +  \frac{4\,A\,C}{7}  +  \frac{2}{3}
% 
\end{align}$$
Solve the system of 5 linear equations :
$$\frac{\partial~\Er }{\partial~ A} = 
\frac{\partial~\Er }{\partial~ B} =  
\frac{\partial~\Er }{\partial~ C} =  
\frac{\partial~\Er }{\partial~ D} =  
\frac{\partial~\Er }{\partial~ E} = 0
$$
To get:
$$A=\frac{105}{128} ,~ B=0 ,~ C=-\frac{105}{64} ,~ D=0 ,~ E=\frac{113}{128} $$

$$\Er\left(\frac{105}{128} ,~ 0 ,~ -\frac{105}{64} ,~ 0 ,~ \frac{113}{128} \right) = \frac{1}{384}$$
