@c DO NOT EDIT!  Generated automatically by munge-texi.

@c Copyright (C) 1996, 1997, 1999, 2002, 2007, 2008, 2009 John W. Eaton
@c
@c This file is part of Octave.
@c
@c Octave is free software; you can redistribute it and/or modify it
@c under the terms of the GNU General Public License as published by the
@c Free Software Foundation; either version 3 of the License, or (at
@c your option) any later version.
@c 
@c Octave is distributed in the hope that it will be useful, but WITHOUT
@c ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
@c FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
@c for more details.
@c 
@c You should have received a copy of the GNU General Public License
@c along with Octave; see the file COPYING.  If not, see
@c <http://www.gnu.org/licenses/>.

@node Numerical Integration
@chapter Numerical Integration

Octave comes with several built-in functions for computing the integral
of a function numerically.  These functions all solve 1-dimensional
integration problems.

@menu
* Functions of One Variable:: 
* Functions of Multiple Variables:: 
* Orthogonal Collocation::      
@end menu

@node Functions of One Variable
@section Functions of One Variable

Octave supports three different algorithms for computing the integral
@tex
$$
 \int_a^b f(x) d x
$$
@end tex
of a function @math{f} over the interval from @math{a} to @math{b}.
These are

@table @code
@item quad
Numerical integration based on Gaussian quadrature.

@item quadl
Numerical integration using an adaptive Lobatto rule.

@item quadgk
Numerical integration using an adaptive Gauss-Konrod rule.

@item quadv
Numerical integration using an adaptive vectorized Simpson's rule.

@item trapz
Numerical integration using the trapezoidal method.
@end table

@noindent
Besides these functions Octave also allows you to perform cumulative
numerical integration using the trapezoidal method through the
@code{cumtrapz} function.

@c ./DLD-FUNCTIONS/quad.cc
@anchor{doc-quad}
@deftypefn {Loadable Function} {[@var{v}, @var{ier}, @var{nfun}, @var{err}] =} quad (@var{f}, @var{a}, @var{b}, @var{tol}, @var{sing})
Integrate a nonlinear function of one variable using Quadpack.
The first argument is the name of the function, the function handle or
the inline function to call to compute the value of the integrand.  It
must have the form

@example
y = f (x)
@end example

@noindent
where @var{y} and @var{x} are scalars.

The second and third arguments are limits of integration.  Either or
both may be infinite.

The optional argument @var{tol} is a vector that specifies the desired
accuracy of the result.  The first element of the vector is the desired
absolute tolerance, and the second element is the desired relative
tolerance.  To choose a relative test only, set the absolute
tolerance to zero.  To choose an absolute test only, set the relative
tolerance to zero.  

The optional argument @var{sing} is a vector of values at which the
integrand is known to be singular.

The result of the integration is returned in @var{v} and @var{ier}
contains an integer error code (0 indicates a successful integration).
The value of @var{nfun} indicates how many function evaluations were
required, and @var{err} contains an estimate of the error in the
solution.

You can use the function @code{quad_options} to set optional
parameters for @code{quad}.

It should be noted that since @code{quad} is written in Fortran it
cannot be called recursively.
@end deftypefn


@c ./DLD-FUNCTIONS/quad.cc
@anchor{doc-quad_options}
@deftypefn {Loadable Function} {} quad_options (@var{opt}, @var{val})
When called with two arguments, this function
allows you set options parameters for the function @code{quad}.
Given one argument, @code{quad_options} returns the value of the
corresponding option.  If no arguments are supplied, the names of all
the available options and their current values are displayed.

Options include

@table @code
@item "absolute tolerance"
Absolute tolerance; may be zero for pure relative error test.
@item "relative tolerance"
Nonnegative relative tolerance.  If the absolute tolerance is zero,
the relative tolerance must be greater than or equal to 
@code{max (50*eps, 0.5e-28)}.
@item "single precision absolute tolerance"
Absolute tolerance for single precision; may be zero for pure relative 
error test.
@item "single precision relative tolerance"
Nonnegative relative tolerance for single precision.  If the absolute
tolerance is zero, the relative tolerance must be greater than or equal to 
@code{max (50*eps, 0.5e-28)}.
@end table
@end deftypefn


Here is an example of using @code{quad} to integrate the function
@tex
$$
 f(x) = x \sin (1/x) \sqrt {|1 - x|}
$$
from $x = 0$ to $x = 3$.
@end tex
@ifnottex

@example
  @var{f}(@var{x}) = @var{x} * sin (1/@var{x}) * sqrt (abs (1 - @var{x}))
@end example

@noindent
from @var{x} = 0 to @var{x} = 3.
@end ifnottex

This is a fairly difficult integration (plot the function over the range
of integration to see why).

The first step is to define the function:

@example
@group
function y = f (x)
  y = x .* sin (1 ./ x) .* sqrt (abs (1 - x));
endfunction
@end group
@end example

Note the use of the `dot' forms of the operators.  This is not necessary
for the call to @code{quad}, but it makes it much easier to generate a
set of points for plotting (because it makes it possible to call the
function with a vector argument to produce a vector result).

Then we simply call quad:

@example
@group
[v, ier, nfun, err] = quad ("f", 0, 3)
     @result{} 1.9819
     @result{} 1
     @result{} 5061
     @result{} 1.1522e-07
@end group
@end example

Although @code{quad} returns a nonzero value for @var{ier}, the result
is reasonably accurate (to see why, examine what happens to the result
if you move the lower bound to 0.1, then 0.01, then 0.001, etc.).

@c ./general/quadl.m
@anchor{doc-quadl}
@deftypefn {Function File} {@var{q} =} quadl (@var{f}, @var{a}, @var{b})
@deftypefnx {Function File} {@var{q} =} quadl (@var{f}, @var{a}, @var{b}, @var{tol})
@deftypefnx {Function File} {@var{q} =} quadl (@var{f}, @var{a}, @var{b}, @var{tol}, @var{trace})
@deftypefnx {Function File} {@var{q} =} quadl (@var{f}, @var{a}, @var{b}, @var{tol}, @var{trace}, @var{p1}, @var{p2}, @dots{})

Numerically evaluate integral using adaptive Lobatto rule.
@code{quadl (@var{f}, @var{a}, @var{b})} approximates the integral of
@code{@var{f}(@var{x})} to machine precision.  @var{f} is either a
function handle, inline function or string containing the name of
the function to evaluate.  The function @var{f} must return a vector
of output values if given a vector of input values.

If defined, @var{tol} defines the relative tolerance to which to
which to integrate @code{@var{f}(@var{x})}.  While if @var{trace} is
defined, displays the left end point of the current interval, the 
interval length, and the partial integral.

Additional arguments @var{p1}, etc., are passed directly to @var{f}.
To use default values for @var{tol} and @var{trace}, one may pass
empty matrices.

Reference: W. Gander and W. Gautschi, 'Adaptive Quadrature - 
Revisited', BIT Vol. 40, No. 1, March 2000, pp. 84--101.
@url{http://www.inf.ethz.ch/personal/gander/}

@end deftypefn


@c ./general/quadgk.m
@anchor{doc-quadgk}
@deftypefn {Function File} {} quadgk (@var{f}, @var{a}, @var{b}, @var{abstol}, @var{trace})
@deftypefnx {Function File} {} quadgk (@var{f}, @var{a}, @var{b}, @var{prop}, @var{val}, @dots{})
@deftypefnx {Function File} {[@var{q}, @var{err}] =} quadgk (@dots{})
Numerically evaluate integral using adaptive Gauss-Konrod quadrature.
The formulation is based on a proposal by L.F. Shampine,
@cite{"Vectorized adaptive quadrature in @sc{matlab}", Journal of
Computational and Applied Mathematics, pp131-140, Vol 211, Issue 2,
Feb 2008} where all function evaluations at an iteration are
calculated with a single call to @var{f}.  Therefore the function
@var{f} must be of the form @code{@var{f} (@var{x})} and accept
vector values of @var{x} and return a vector of the same length
representing the function evaluations at the given values of @var{x}.
The function @var{f} can be defined in terms of a function handle,
inline function or string.

The bounds of the quadrature @code{[@var{a}, @var{b}]} can be finite
or infinite and contain weak end singularities.  Variable
transformation will be used to treat infinite intervals and weaken
the singularities.  For example

@example
quadgk(@@(x) 1 ./ (sqrt (x) .* (x + 1)), 0, Inf)
@end example

@noindent
Note that the formulation of the integrand uses the
element-by-element operator @code{./} and all user functions to
@code{quadgk} should do the same.

The absolute tolerance can be passed as a fourth argument in a manner
compatible with @code{quadv}.  Equally the user can request that
information on the convergence can be printed is the fifth argument
is logically true.

Alternatively, certain properties of @code{quadgk} can be passed as
pairs @code{@var{prop}, @var{val}}.  Valid properties are

@table @code
@item AbsTol
Defines the absolute error tolerance for the quadrature.  The default
absolute tolerance is 1e-10.

@item RelTol
Defines the relative error tolerance for the quadrature.  The default
relative tolerance is 1e-5.

@item MaxIntervalCount
@code{quadgk} initially subdivides the interval on which to perform
the quadrature into 10 intervals.  Sub-intervals that have an
unacceptable error are sub-divided and re-evaluated.  If the number of
sub-intervals exceeds at any point 650 sub-intervals then a poor
convergence is signaled and the current estimate of the integral is
returned.  The property 'MaxIntervalCount' can be used to alter the
number of sub-intervals that can exist before exiting.

@item WayPoints
If there exists discontinuities in the first derivative of the
function to integrate, then these can be flagged with the
@code{"WayPoints"} property.  This forces the ends of a sub-interval
to fall on the breakpoints of the function and can result in
significantly improved estimation of the error in the integral, faster
computation or both.  For example,

@example
quadgk (@@(x) abs (1 - x .^ 2), 0, 2, 'Waypoints', 1)
@end example

@noindent
signals the breakpoint in the integrand at @code{@var{x} = 1}.

@item Trace
If logically true, then @code{quadgk} prints information on the
convergence of the quadrature at each iteration.
@end table

If any of @var{a}, @var{b} or @var{waypoints} is complex, then the
quadrature is treated as a contour integral along a piecewise
continuous path defined by the above.  In this case the integral is
assumed to have no edge singularities.  For example

@example
@group
quadgk (@@(z) log (z), 1+1i, 1+1i, "WayPoints",
        [1-1i, -1,-1i, -1+1i])
@end group
@end example

@noindent
integrates @code{log (z)} along the square defined by @code{[1+1i,
 1-1i, -1-1i, -1+1i]}

If two output arguments are requested, then @var{err} returns the
approximate bounds on the error in the integral @code{abs (@var{q} -
@var{i})}, where @var{i} is the exact value of the integral.

@seealso{@ref{doc-triplequad,,triplequad}, @ref{doc-dblquad,,dblquad}, @ref{doc-quad,,quad}, @ref{doc-quadl,,quadl}, @ref{doc-quadv,,quadv}, @ref{doc-trapz,,trapz}}
@end deftypefn


@c ./general/quadv.m
@anchor{doc-quadv}
@deftypefn {Function File} {@var{q} =} quadv (@var{f}, @var{a}, @var{b})
@deftypefnx {Function File} {@var{q} =} quadl (@var{f}, @var{a}, @var{b}, @var{tol})
@deftypefnx {Function File} {@var{q} =} quadl (@var{f}, @var{a}, @var{b}, @var{tol}, @var{trace})
@deftypefnx {Function File} {@var{q} =} quadl (@var{f}, @var{a}, @var{b}, @var{tol}, @var{trace}, @var{p1}, @var{p2}, @dots{})
@deftypefnx {Function File} {[@var{q}, @var{fcnt}] =} quadl (@dots{})

Numerically evaluate integral using adaptive Simpson's rule.
@code{quadv (@var{f}, @var{a}, @var{b})} approximates the integral of
@code{@var{f}(@var{x})} to the default absolute tolerance of @code{1e-6}. 
@var{f} is either a function handle, inline function or string
containing the name of the function to evaluate.  The function @var{f}
must accept a string, and can return a vector representing the
approximation to @var{n} different sub-functions.

If defined, @var{tol} defines the absolute tolerance to which to
which to integrate each sub-interval of @code{@var{f}(@var{x})}.
While if @var{trace} is defined, displays the left end point of the
current interval, the interval length, and the partial integral.

Additional arguments @var{p1}, etc., are passed directly to @var{f}.
To use default values for @var{tol} and @var{trace}, one may pass
empty matrices.
@seealso{@ref{doc-triplequad,,triplequad}, @ref{doc-dblquad,,dblquad}, @ref{doc-quad,,quad}, @ref{doc-quadl,,quadl}, @ref{doc-quadgk,,quadgk}, @ref{doc-trapz,,trapz}}
@end deftypefn


@c ./general/trapz.m
@anchor{doc-trapz}
@deftypefn {Function File} {@var{z} =} trapz (@var{y})
@deftypefnx {Function File} {@var{z} =} trapz (@var{x}, @var{y})
@deftypefnx {Function File} {@var{z} =} trapz (@dots{}, @var{dim})

Numerical integration using trapezoidal method.  @code{trapz
(@var{y})} computes the integral of the @var{y} along the first
non-singleton dimension.  If the argument @var{x} is omitted a 
equally spaced vector is assumed.  @code{trapz (@var{x}, @var{y})} 
evaluates the integral with respect to @var{x}.
 
@seealso{@ref{doc-cumtrapz,,cumtrapz}}
@end deftypefn


@c ./general/cumtrapz.m
@anchor{doc-cumtrapz}
@deftypefn {Function File} {@var{z} =} cumtrapz (@var{y})
@deftypefnx {Function File} {@var{z} =} cumtrapz (@var{x}, @var{y})
@deftypefnx {Function File} {@var{z} =} cumtrapz (@dots{}, @var{dim})

Cumulative numerical integration using trapezoidal method.
@code{cumtrapz (@var{y})} computes the cumulative integral of the 
@var{y} along the first non-singleton dimension.  If the argument 
@var{x} is omitted a equally spaced vector is assumed.  @code{cumtrapz 
(@var{x}, @var{y})} evaluates the cumulative integral with respect 
to @var{x}.
 
@seealso{@ref{doc-trapz,,trapz}, @ref{doc-cumsum,,cumsum}}
@end deftypefn


@node Orthogonal Collocation
@section Orthogonal Collocation

@c ./DLD-FUNCTIONS/colloc.cc
@anchor{doc-colloc}
@deftypefn {Loadable Function} {[@var{r}, @var{amat}, @var{bmat}, @var{q}] =} colloc (@var{n}, "left", "right")
Compute derivative and integral weight matrices for orthogonal
collocation using the subroutines given in J. Villadsen and
M. L. Michelsen, @cite{Solution of Differential Equation Models by
Polynomial Approximation}.
@end deftypefn


Here is an example of using @code{colloc} to generate weight matrices
for solving the second order differential equation
@tex
$u^\prime - \alpha u^{\prime\prime} = 0$ with the boundary conditions
$u(0) = 0$ and $u(1) = 1$.
@end tex
@ifnottex
@var{u}' - @var{alpha} * @var{u}'' = 0 with the boundary conditions
@var{u}(0) = 0 and @var{u}(1) = 1.
@end ifnottex

First, we can generate the weight matrices for @var{n} points (including
the endpoints of the interval), and incorporate the boundary conditions
in the right hand side (for a specific value of
@tex
$\alpha$).
@end tex
@ifnottex
@var{alpha}).
@end ifnottex

@example
@group
n = 7;
alpha = 0.1;
[r, a, b] = colloc (n-2, "left", "right");
at = a(2:n-1,2:n-1);
bt = b(2:n-1,2:n-1);
rhs = alpha * b(2:n-1,n) - a(2:n-1,n);
@end group
@end example

Then the solution at the roots @var{r} is

@example
@group
u = [ 0; (at - alpha * bt) \ rhs; 1]
     @result{} [ 0.00; 0.004; 0.01 0.00; 0.12; 0.62; 1.00 ]
@end group
@end example

@node Functions of Multiple Variables
@section Functions of Multiple Variables

Octave does not have built-in functions for computing the integral of
functions of multiple variables directly.  It is however possible to
compute the integral of a function of multiple variables using the
functions for one-dimensional integrals.

To illustrate how the integration can be performed, we will integrate
the function
@tex
$$
  f(x, y) = \sin(\pi x y)\sqrt{x y}
$$
@end tex
@ifnottex
@example
f(x, y) = sin(pi*x*y)*sqrt(x*y)
@end example
@end ifnottex
for @math{x} and @math{y} between 0 and 1.

The first approach creates a function that integrates @math{f} with
respect to @math{x}, and then integrates that function with respect to
@math{y}.  Since @code{quad} is written in Fortran it cannot be called
recursively.  This means that @code{quad} cannot integrate a function
that calls @code{quad}, and hence cannot be used to perform the double
integration.  It is however possible with @code{quadl}, which is what
the following code does.

@example
@group
function I = g(y)
  I = ones(1, length(y));
  for i = 1:length(y)
    f = @@(x) sin(pi.*x.*y(i)).*sqrt(x.*y(i));
    I(i) = quadl(f, 0, 1);
  endfor
endfunction

I = quadl("g", 0, 1)
      @result{} 0.30022
@end group
@end example

The above process can be simplified with the @code{dblquad} and
@code{triplequad} functions for integrals over two and three
variables.  For example

@example
@group
I =  dblquad (@@(x, y) sin(pi.*x.*y).*sqrt(x.*y), 0, 1, 0, 1)
      @result{} 0.30022
@end group
@end example

@c ./general/dblquad.m
@anchor{doc-dblquad}
@deftypefn {Function File} {} dblquad (@var{f}, @var{xa}, @var{xb}, @var{ya}, @var{yb}, @var{tol}, @var{quadf}, @dots{})
Numerically evaluate a double integral.  The function over with to
integrate is defined by @code{@var{f}}, and the interval for the
integration is defined by @code{[@var{xa}, @var{xb}, @var{ya},
@var{yb}]}.  The function @var{f} must accept a vector @var{x} and a
scalar @var{y}, and return a vector of the same length as @var{x}. 

If defined, @var{tol} defines the absolute tolerance to which to
which to integrate each sub-integral.

Additional arguments, are passed directly to @var{f}.  To use the default
value for @var{tol} one may pass an empty matrix.
@seealso{@ref{doc-triplequad,,triplequad}, @ref{doc-quad,,quad}, @ref{doc-quadv,,quadv}, @ref{doc-quadl,,quadl}, @ref{doc-quadgk,,quadgk}, @ref{doc-trapz,,trapz}}
@end deftypefn


@c ./general/triplequad.m
@anchor{doc-triplequad}
@deftypefn {Function File} {} triplequad (@var{f}, @var{xa}, @var{xb}, @var{ya}, @var{yb}, @var{za}, @var{zb}, @var{tol}, @var{quadf}, @dots{})
Numerically evaluate a triple integral.  The function over which to
integrate is defined by @code{@var{f}}, and the interval for the
integration is defined by @code{[@var{xa}, @var{xb}, @var{ya},
@var{yb}, @var{za}, @var{zb}]}.  The function @var{f} must accept a
vector @var{x} and a scalar @var{y}, and return a vector of the same
length as @var{x}.

If defined, @var{tol} defines the absolute tolerance to which to
which to integrate each sub-integral.

Additional arguments, are passed directly to @var{f}.  To use the default
value for @var{tol} one may pass an empty matrix.
@seealso{@ref{doc-dblquad,,dblquad}, @ref{doc-quad,,quad}, @ref{doc-quadv,,quadv}, @ref{doc-quadl,,quadl}, @ref{doc-quadgk,,quadgk}, @ref{doc-trapz,,trapz}}
@end deftypefn


The above mentioned approach works but is fairly slow, and that problem
increases exponentially with the dimensionality the problem.  Another
possible solution is to use Orthogonal Collocation as described in the
previous section.  The integral of a function @math{f(x,y)} for
@math{x} and @math{y} between 0 and 1 can be approximated using @math{n}
points by
@tex
$$
 \int_0^1 \int_0^1 f(x,y) d x d y \approx \sum_{i=1}^n \sum_{j=1}^n q_i q_j f(r_i, r_j),
$$
@end tex
@ifnottex
the sum over @code{i=1:n} and @code{j=1:n} of @code{q(i)*q(j)*f(r(i),r(j))},
@end ifnottex
where @math{q} and @math{r} is as returned by @code{colloc(n)}.  The
generalization to more than two variables is straight forward.  The
following code computes the studied integral using @math{n=7} points.

@example
@group
f = @@(x,y) sin(pi*x*y').*sqrt(x*y');
n = 7;
[t, A, B, q] = colloc(n);
I = q'*f(t,t)*q;
      @result{} 0.30022
@end group
@end example

@noindent
It should be noted that the number of points determines the quality
of the approximation.  If the integration needs to be performed between
@math{a} and @math{b} instead of 0 and 1, a change of variables is needed.



