NIntegrate

NIntegrate[f,{x,xmin,xmax}]

gives a numerical approximation to the integral .

NIntegrate[f,{x,xmin,xmax},{y,ymin,ymax},]

gives a numerical approximation to the multiple integral .

NIntegrate[f,{x,y,}reg]

integrates over the geometric region reg.

Details and Options

  • Multiple integrals use a variant of the standard iterator notation. The first variable given corresponds to the outermost integral and is done last.
  • NIntegrate by default tests for singularities at the boundaries of the integration region and at the boundaries of regions specified by settings for the Exclusions option.
  • NIntegrate[f,{x,x0,x1,,xk}] tests for singularities in a one-dimensional integral at each of the intermediate points xi. If there are no singularities, the result is equivalent to an integral from x0 to xk. You can use complex numbers xi to specify an integration contour in the complex plane.
  • The following options can be given:
  • AccuracyGoalInfinitydigits of absolute accuracy sought
    EvaluationMonitorNoneexpression to evaluate whenever expr is evaluated
    ExclusionsNoneparts of the integration region to exclude
    MaxPointsAutomaticmaximum total number of sample points
    MaxRecursionAutomaticmaximum number of recursive subdivisions
    MethodAutomaticmethod to use
    MinRecursion0minimum number of recursive subdivisions
    PrecisionGoalAutomaticdigits of precision sought
    WorkingPrecisionMachinePrecisionthe precision used in internal computations
  • NIntegrate usually uses adaptive algorithms, which recursively subdivide the integration region as needed. MinRecursion specifies the minimum number of recursive subdivisions to try. MaxRecursion gives the maximum number.
  • NIntegrate usually continues doing subdivisions until the error estimate it gets implies that the final result achieves either the AccuracyGoal or the PrecisionGoal specified.
  • For low-dimensional integrals, the default setting for PrecisionGoal is related to WorkingPrecision. For high-dimensional integrals, it is typically taken to be a fixed value, usually 2.
  • You should realize that with sufficiently pathological functions, the algorithms used by NIntegrate can give wrong answers. In most cases, you can test the answer by looking at its sensitivity to changes in the setting of options for NIntegrate.
  • Possible explicit settings for the Method option include:
  • "GlobalAdaptive"global adaptive integration strategy
    "LocalAdaptive"local adaptive integration strategy
    "DoubleExponential"double exponential quadrature
    "MonteCarlo"Monte Carlo integration
    "AdaptiveMonteCarlo"adaptive Monte Carlo integration
    "QuasiMonteCarlo"quasi Monte Carlo integration
    "AdaptiveQuasiMonteCarlo"adaptive quasi Monte Carlo integration
  • With Method->{"strategy",Method->"rule"} or Method->{"strategy",Method->{rule1,rule2,}} possible strategy methods include:
  • "GlobalAdaptive"subdivide based on global error estimates
    "LocalAdaptive"subdivide based only on local error estimates
  • Methods used as rules include:
  • "CartesianRule"multidimensional product of rules
    "ClenshawCurtisRule"ClenshawCurtis rule
    "GaussKronrodRule"Gauss points with Kronrod extension
    "LevinRule"Levin-type oscillatory rules
    "LobattoKronrodRule"GaussLobatto points with Kronrod extension
    "MultidimensionalRule"multidimensional symmetric rule
    "MultipanelRule"combination of 1D rules
    "NewtonCotesRule"NewtonCotes rule
    "RiemannRule"Riemann sum rule
    "TrapezoidalRule"uniform points in one dimension
  • With the setting Method->"rule", the strategy method will be selected automatically.
  • Additional method suboptions can be given in the form Method->{,opts}.
  • NIntegrate symbolically analyzes its input to transform oscillatory and other integrands, subdivide piecewise functions, and select optimal algorithms.
  • The method suboption "SymbolicProcessing" specifies the maximum number of seconds for which to attempt performing symbolic analysis of the integrand.
  • N[Integrate[]] calls NIntegrate for integrals that cannot be done symbolically.
  • NIntegrate first localizes the values of all variables, then evaluates f with the variables being symbolic, and then repeatedly evaluates the result numerically.
  • NIntegrate has attribute HoldAll and effectively uses Block to localize variables.

Examples

open allclose all

Basic Examples  (5)

Compute a numerical integral:

Compute a multidimensional integral (with singularity at the origin):

Compute areas and volumes for implicitly defined regions:

Integrate over any region:

Integrate oscillatory and other complicated functions:

Scope  (56)

Basic Uses  (12)

Integrate functions over a finite real range:

An infinite real range:

Get results at high precision:

Integrate along a complex line, finite or infinite:

Along a piecewise linear contour in the complex plane:

Along a circular contour in the complex plane:

Plot the real part of a function and paths of integration:

Vector- and tensor-valued functions:

Multivariate functions:

The bounds for an integration variable can depend on the previous variables:

Plot the integrand over the integration region:

Integrate over regions defined by inequalities:

Plot the integration region:

Integrate over any geometric region including special regions:

Formula regions:

Mesh regions:

Find the volume of the unit ball in five dimensions:

The surface area of the standard cylinder, by computing a surface integral:

The length of an ellipse, by computing a line integral:

Multivariate integrals using Monte Carlo methods:

Singular Integrals  (9)

Integrate functions with algebraic singularities at the endpoints:

Plot over the integration range:

Logarithmic singularities at endpoints:

Plot over the integration range:

Singularities at both endpoints:

Plot over the integration range:

Test for singularities interior to the integration region using Exclusions:

Plot over the integration range:

Multivariate integrals of functions with singularities at edges and corners:

Plot over the integration range:

Singularities at the corners of multidimensional integration regions:

Plot over the integration range:

Multivariate integral with a singularity at an interior point:

Several interior point singularities:

Plot over the integration range:

Multivariate integral of a function that is singular at curves satisfying an equation:

Plot over the integration range:

Cauchy principal value of functions with non-integrable singularities:

Piecewise Integrals  (9)

Piecewise functions with finitely many cases:

Piecewise functions with infinitely many cases:

Composition with any other function:

Use Exclusions to explicitly specify discontinuities or sharp corners:

Plot over the integration range:

Multivariate piecewise integrals with finitely many cases:

Explicitly specify discontinuities and sharp corners:

Plot real and imaginary parts over the region:

Integrate over 2D regions:

Integrate over 3D regions:

Integrate over -dimensional regions:

Oscillatory Integrals  (15)

Integrating a highly oscillatory elementary function over a finite range:

Plot over the range:

Highly oscillatory special functions:

Plot over the range:

Integrate oscillatory functions over an infinite range:

Oscillatory special functions over an infinite range:

Sums of oscillatory functions:

Plot over the range:

Products of oscillatory functions:

Plot over the range:

Powers of oscillatory functions:

Plot over the range:

Compositions of oscillatory functions with non-oscillatory ones:

Plot over the integration range:

Sums, products, powers, and compositions of oscillatory functions:

Plot over part of the integration range:

Multivariate integrals of highly oscillatory elementary functions over a finite range:

Plot over one millionth of the range:

Multivariate integrals of oscillatory special functions over a finite range:

Multivariate oscillatory functions over an infinite range:

Singular oscillatory functions:

Plot over the range:

Composition of oscillatory functions with singular ones:

Plot over the integration range:

Piecewise oscillatory functions:

Plot at the oscillation rate:

Piecewise oscillatory functions with singularities:

Plot over the integration range:

Region Integrals  (11)

Different ways of integrating over a unit disk:

Visualize the integrand over the region:

More general integral over a unit disk:

Visualize the integrand over the region:

Integration over a 0D region corresponds to summing over the points:

Integration over a 1D region corresponds to a curve integral:

Integration over a 2D region corresponds to a surface integral:

In general, integrals over lower-dimensional regions correspond to surface integrals:

The region is lower dimensional:

Integrate over any basic region including a filled parallelogram:

A filled cone:

A sphere surface:

A filled ellipsoid:

A half-infinite line:

Integrate over any ImplicitRegion:

A full-dimensional region:

Integrate over any ParametricRegion:

A full-dimensional region:

Integrate over any MeshRegion:

Regions in 2D:

Regions in 3D:

Integrate over any BoundaryMeshRegion:

Options  (30)

AccuracyGoal  (1)

The AccuracyGoal option can be used to change the default absolute tolerance:

The integration process stops once the accuracy goal criterion has been exceeded:

The result with the default settings is different since the default uses only a precision criterion:

EvaluationMonitor  (2)

Get the number of evaluation points used in a numerical integration:

Show the evaluation points used in a numerical integration:

Exclusions  (1)

Integration by excluding the curves on which the integrand's denominator is zero:

The curves on which the integrand is singular:

MaxPoints  (1)

Stop integration after a specified number of points has been exceeded:

MaxRecursion  (1)

Without enough adaptive recursion, the following gives a poor result:

Specifying a larger value for MaxRecursion gives a much better result:

Specifying the singularity locations is even more efficient:

Method  (21)

Integration Rules  (10)

Left- and right-sided Riemann sum:

Riemann sum samples uniformly at the left or right endpoints of subregions:

Basic trapezoidal rule with no extrapolation, corresponding to piecewise linear approximation:

Trapezoidal rule with Romberg extrapolation:

The basic trapezoidal rule samples uniformly (when adaptivity is turned off):

Default adaptive method with trapezoidal rule:

NewtonCotes rule with evenly spaced sampling points:

Closed formulas include endpoints, but open formulas do not:

A NewtonCotes rule corresponds to polynomial interpolation:

The approximation with no adaptivity is the same as integrating the corresponding polynomial:

The method with order is exact for polynomials up to degree :

ClenshawCurtis quadrature rule with the strategy selected automatically:

The sampling points are nonuniform:

The points are rescaled versions of :

Gaussian quadrature rule with Kronrod extension for error estimation:

Gaussian rules use nonuniform sample points:

The method with Gauss points is exact for polynomials of degree :

The method with order uses enough points to be exact for polynomials of degree :

Gaussian quadrature rule at Lobatto points with Kronrod extension:

Lobatto points are nonuniform and include the endpoints of the integration region:

Multipanel rule (or composite rule) applies the specified rule to multiple subintervals:

Any other rule can be used together with a multipanel rule:

Using the product of one-dimensional rules:

A list of rules is automatically interpreted as a product of rules:

Use uniform sampling in x and nonuniform sampling in y:

Multivariate integration using a multidimensional symmetric rule:

The multidimensional rule uses a sparse symmetric grid of sample points:

Increase the number of sample points:

Timing can sometimes be improved with a different number of generators:

Integration of an oscillatory function using a Levin-type collocation rule:

Multivariate Levin-type rule:

Integration Strategies  (6)

Globally adaptive integration strategy:

Subdivide regions based on largest error until global error is sufficiently small:

Locally adaptive integration strategy:

Subdivide every region until all local errors are sufficiently small:

Trapezoidal strategy that samples uniformly at increasing density:

Subdivide entire region and use a lower-order method:

Double-exponential ("tanh-sinh") strategy that samples densely near the endpoints:

Subdivide entire region, after transformation:

Monte Carlo integration with uniformly random sampling points:

With deterministic sequences of sampling points:

Globally adaptive versions of Monte Carlo and quasi Monte Carlo:

Plot sampling points used by different strategies:

Symbolic Processing  (5)

By default some symbolic processing may be performed:

Use the automatic numeric methods, but no symbolic processing:

Use an explicit time limit for symbolic processing:

Control automatic subdivision of piecewise functions:

Automatic subdivision of piecewise functions usually leads to fewer function evaluations:

Control automatic simplification of even and odd integrands:

Automatic simplification usually leads to fewer function evaluations:

Control automatic method selection for highly oscillatory functions:

Specialized methods lead to fewer function evaluations for highly oscillatory functions:

Switching detection off can save time for non-oscillatory functions:

Control automatic subdivision at nodes of interpolating functions:

Subdivision of interpolating functions can lead to fewer evaluations:

Subdivision may be unnecessary for an accurate interpolation of a smooth function:

MinRecursion  (1)

NIntegrate may miss sharp peaks of integrands:

Increasing MinRecursion forces a finer subdivision of the integration region:

PrecisionGoal  (1)

The number of samples used to evaluate for different relative tolerances:

The number of samples needed typically increases exponentially with the PrecisionGoal:

WorkingPrecision  (1)

NIntegrate can compute integrals using higher working precision:

The PrecisionGoal used is 10 less than the WorkingPrecision:

Applications  (26)

Basic Applications  (2)

Compute an integral that has no closed-form solution:

Integrate a discrete set of data using Interpolation:

Integrate also works on interpolating functions:

Plot the data and the interpolation:

Probability and Expectation  (3)

Compute the probability that when follows a standard normal distribution:

Use NProbability directly:

Compute the expectation of sqrt(TemplateBox[{x}, Abs]) when follows a standard Cauchy distribution:

Use NExpectation directly:

Compute the cumulative distribution function (CDF) from the probability density function (PDF):

Compute a quantile value by solving an equation:

Use Quantile directly:

Lengths, Areas, and Volumes  (7)

Compute the area between two curves as a one-dimensional integral of their difference:

As a two-dimensional integral over the region bounded by them:

Plot the computed area:

Compute the area of a disk that is given implicitly:

Disk annulus:

Ellipse:

Ellipse annulus:

Disk segment:

Simple regions including a ball:

Half of a spherical shell:

Ellipsoid:

Half of an ellipsoidal shell:

Spherical wedge:

Compute the area of a region defined by a closed parametric curve using Green's theorem:

Ellipse:

A periodic boundary curve:

Compute the length of a parametric curve:

Ellipse:

A periodic boundary curve:

A circle in 3D:

Ellipse in 3D:

More general curve:

A toroidal spring curve:

Compute the area of a parametrically defined surface:

Ellipsoidal surface:

Toroidal surface:

General parametric surface:

Compute the volume enclosed by a parametric surface using the divergence theorem:

Ellipsoidal volume:

Toroidal volume:

Volume of a general parametric surface:

Line, Surface, and Volume Integrals  (3)

Work done by a cyclic thermodynamic process:

Visualize cycle on a pressure-volume diagram:

Mass and center of mass of a region with uniform density:

Visualize the center of mass:

Three-dimensional region:

Visualize the center of mass:

Center of mass of a region enclosed by a parametric surface using Stokes's theorem:

Visualize center of mass:

Integral Transforms  (4)

Compute integral transforms including Fourier transform:

Laplace transform:

Mellin transform:

Hilbert transform:

Hartley transform:

Find the Fourier coefficients of a periodic function on [0,1]:

Show the approximate inverse transform:

Compute a quadratic fractional Fourier transform:

Fraunhofer integral for amplitude of waves diffracted by a square aperture:

Diffraction pattern near optical axis:

Integral Representations of Special Functions  (3)

Integral representation for Bessel function of the first kind TemplateBox[{n, z}, BesselJ] on the real line:

Compare with built-in function BesselJ[n,x]:

Gamma function TemplateBox[{z}, Gamma] on the right half of the complex plane:

Compare with built-in function Gamma[z]:

Incomplete elliptic integral of the second kind TemplateBox[{z, m}, EllipticE2] on the real line:

Compare with built-in function EllipticE[z,m]:

Function Norms and Inner Products  (2)

norm of a function:

Plot norm as a function of :

Minimize TemplateBox[{f}, Norm]_p as a function of :

inner product with respect to weight function for functions defined on :

Orthogonality of Legendre polynomials TemplateBox[{n, x}, LegendreP] on with weight function 1:

Orthogonality of Chebyshev polynomials on with weight function :

Orthogonality of Hermite polynomials on with weight function :

Complex Analysis  (2)

Compute the residue of at as an integral over a contour enclosing :

Compare with exact value:

Numerical derivative of a function at as an integral over a contour enclosing :

Differentiate a function defined numerically:

Properties & Relations  (9)

NIntegrate computes a surface integral for lower-dimensional regions:

The regions are lower dimensional:

The surface (curve etc.) integral for a parametric surface is given by the ordinary integral where is the Gram determinant:

Integrating over a parametric circle curve :

Integrating over a parametric sphere surface :

Integrating over a zero-dimensional region corresponds to summing over the points:

When a closed-form solution is available, Integrate can be used instead of NIntegrate:

The result of NIntegrate is close to the exact value:

NDSolve can be used instead of NIntegrate:

NIntegrate will typically give a more precise result since it uses global error control:

Approximate the tail of a sum using the EulerMaclaurin formula:

The EulerMaclaurin formula approximation compares well with the exact result:

The EulerMaclaurin method of NSum uses Integrate or NIntegrate:

Find a cumulative distribution function from a probability density function:

CDF gives the same result:

The Residue of a function at a pole is equivalent to a contour integral:

Numerically integrate on a contour that includes the real axis from - to :

Several special functions are defined as integrals:

For high precision, using the special function is usually preferable:

Possible Issues  (6)

For integrands with complicated variation, many levels of adaptive recursion may be required:

Specifying higher recursive subdivision levels gives a convergent result:

One-dimensional integral with a singularity inside the integration region:

Specify the location of the singularity to handle it with appropriate transformations:

Since the default is to use relative tolerance, integrals that are zero may be computed slowly:

Specifying an absolute tolerance with AccuracyGoal will reduce the amount of work:

Higher-dimensional cubature-based integration to default precision may be slow:

Decreasing the PrecisionGoal speeds up the computation:

Using a quasi Monte Carlo method for the same low PrecisionGoal may be even faster:

NIntegrate automatically uses Monte Carlo integration for dimensions higher than 15:

It can be time-consuming to compute functions symbolically:

Restricting the function definition avoids symbolic evaluation:

Define a function that does numerical integration for a given parameter:

Compute with a parameter value of 2:

Applying the function to a symbolic parameter generates a message from NIntegrate:

This can also lead to warnings when the function is used with other numerical functions like NMinimize:

Define a function that only evaluates when its argument is a numerical value to avoid these messages:

Compute with a numerical value:

The function does not evaluate when its argument is non-numerical:

The function can now be used with other numerical functions such as NMinimize:

Neat Examples  (2)

Sampling points for a three-dimensional integration, using a low-order method:

Integrate a function with several singular curves:

Introduced in 1988
 (1.0)
 |
Updated in 1996
 (3.0)
2003
 (5.0)
2007
 (6.0)
2010
 (8.0)
2014
 (10.0)