function ccfi_sparse_test ( )

%*****************************************************************************80
%
%% ccfi_sparse_test() uses ccfi() to build a sparse grid.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    21 May 2014
%
%  Author:
%
%    John Burkardt
%
%  Local:
%
%    integer D, the spatial dimension.
%
%    integer MAXK, the maximum level to check.
%
  d = 10;
  maxk = 5;
  trueval = 1.0;

  fprintf ( 1, '\n' );
  fprintf ( 1, 'ccfi_sparse_test():\n' );
  fprintf ( 1, '  ccfi() builds a sparse grid:\n' );
  fprintf ( 1, '  Sparse nested quadrature for a D-dimensional integral:\n' );
  fprintf ( 1, '    integral ( 0 <= x < +oo ) f(x) exp(-x) dx\n' );
  fprintf ( 1, '  Exact integral should be %g\n', trueval );
  fprintf ( 1, '\n' );
  fprintf ( 1, '   D  Level   Nodes    SG estimate MC estimate\n' );
  fprintf ( 1, '                       SG error    MC error\n' );
  fprintf ( 1, '\n' );

  for k = 1 : maxk
%
%  Compute sparse grid estimate.
%
    [ x, w ] = nwspgr ( 'ccfi', d, k );
    [ n, ~ ] = size ( x );
    fx = flunk ( x );
    sgappr = w' * fx;
    sgerror = sqrt ( ( sgappr - trueval ).^2 ) / trueval;
%
%  Average 1000 Monte Carlo estimates. 
%  Draw from an exponential distribution, (-log(rand()))
%  and average.
%
    sim = zeros ( 1000, 1 );
    for r = 1 : 1000
      x = - log ( rand ( n, d ) );
      fx = flunk ( x );
      sim(r) = mean ( fx );
    end
    simerror = sqrt ( mean ( ( sim - trueval ).^2 ) ) / trueval;

    fprintf ( '  %2d     %2d  %6d  %10.5g  %10.5g\n', ...
      d, k, n, sgappr, mean ( sim ) )
    fprintf ( '                     %10.5g  %10.5g\n', ...
      sgerror, simerror )

  end

  return
end
function value = flunk ( x )

%*****************************************************************************80
%
%% flunk() evaluates the Laguerre integrand function 1.
%
%  Discussion:
%
%    I don't know any good test integrands for Laguerre integration in
%    multiple dimensions, so I am starting with this one:
%      integral ( 0 <= x < +oo ) 1 exp(-x) dx = 1
%    where x is an M-dimensional vector.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    22 May 2014
%
%  Author:
%
%    John Burkardt
%
%  Input:
%
%    real X, the evaluation points.
%
%  Output:
%
%    real VALUE, the integrand values.
%
  [ n, m ] = size ( x );
  value = ones ( n, 1 );

  return
end
 
