I'm trying to find the best approximation to the function $e^x$ in the finite dimensional polynomial space $P_4$ with respect to the standard basis vectors $B=\{1,x,x^2,x^3,x^4\}$ with inner product $$(f,g)=\int_0^1 \frac{f(x)g(x)}{\left(x(1-x)\right)^{\frac{1}{2}}}dx$$
Let $w=\sum_{j=0}^4a_j\phi_j $ where $\phi_j=x^j$. Then, the best approximation of $w$ to $e^x$ satisfies the orthogonality property:
$$(e^x-w,\phi_i)=0$$ for $i=0,...,4$. Hence,
$$\sum_{j=0}^4 a_j (\phi_j,\phi_i) = (e^x,\phi_i)$$ for $i=0,...,4.$. This generates linear system of equations which I'm trying to solve. Unfortunately, the integrals are a bit difficult to evaluate by hand. So, I tried using a three point gaussian quadrature rule to approximate the integrals and solve the system. Unfortunately, I keep getting a nearly singular system. When I observed this, I tried using a higher order quadrature rule, but the matrix remains ill-conditioned.
I looked at my code over and over again and I can't seem to find any errors in the implementation. I'm tempted to believe that these inner products simply can't be evaluated well with a gaussian quadrature rule. Is this common for Gram Matrices? Should I use a different quadrature rule? Or is it a bug in my code?
I have provided my matlab code assembing this matrix system below for reference. Any help would be greatly appreciated.
n=5;
%Quadrature points on [-1,1]
z1=-sqrt(3/5);
z2=0;
z3=sqrt(3/5);
%Quadrature points on [0,1]
x1=z1/2+1/2;
x2=z2/2+1/2;
x3=z3/2+1/2;
A=zeros(n,n);
b=zeros(n,1);
%assemble gramm matrix
for i=1:n
for j=1:n
F1=x1^(i-1+j-1)/sqrt(x1*(1-x1));
F2=x2^(i-1+j-1)/sqrt(x2*(1-x2));
F3=x3^(i-1+j-1)/sqrt(x3*(1-x3));
A(i,j)=(1/2)*((5/9)*F1+(8/9)*F2+(5/9)*F3);
end
G1=x1^(i-1)*exp(x1)/sqrt(x1*(1-x1));
G2=x2^(i-1)*exp(x2)/sqrt(x2*(1-x2));
G3=x3^(i-1)*exp(x3)/sqrt(x3*(1-x3));
b(i)=(1/2)*((5/9)*G1+(8/9)*G2+(5/9)*G3);
end