function c = monomial_approximate ( f, d )

%*****************************************************************************80
%
%% monomial_approximate: least squares approximant to f(x) in [-1,+1].
%
%  Input:
%
%    function f(x): a function handle.
%
%    integer d: the highest degree monomial to use.
%
%  Output:
%
%    real c(d+1): the coefficients of the approximant polynomial.
%
  A = zeros ( d+1, d+1 );
  for i = 0 : d
    for j = 0 : d
      A(i+1,j+1) = integral ( @(x) x.^i .* x.^j, -1.0, +1.0 );
    end
  end
  
  b = zeros ( d+1, 1 );
  for i = 0 : d
    b(i+1) = integral ( @(x) x.^i .* f(x), -1.0, +1.0 );
  end

  c = A \ b;
  cr = c(d+1:-1:1);
  e = integral ( @(x) ( polyval(cr,x) - f(x) ).^2, -1.0, +1.0 );
  fprintf ( 1, '  L2 norm of approximation error = %g\n', sqrt ( e ) );
  
  return
end

