function c = legendre_approximate ( f, d )

%*****************************************************************************80
%
%% legendre_approximate uses the Legendre basis to approximate a function.
%
%  Input:
%
%    function f: the function to be approximated.
%
%    integer d: the highest degree of the polynomials.
%
%  Output:
%
%    real c(d+1): the Legendre coefficients of the approximation.
%
  c = zeros ( d + 1, 1 );
  for i = 0 : d
    fp = integral ( @(x) f(x) .* legendre_value ( i, x ), -1.0, +1.0 );
    pp = integral ( @(x) ( legendre_value ( i, x ) ).^2, -1.0, +1.0 );
    c(i+1) = fp / pp;
  end

  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

