Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #10489

Re: Bug in NIntegrate[]?

From Andrzej Kozlowski <akozlowski@gmail.com>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Bug in NIntegrate[]?
Date 2012-06-15 19:38 +0000
Organization Steven M. Christensen and Associates, Inc and MathTensor, Inc.
Message-ID <jrg2ve$so6$1@smc.vnet.net> (permalink)
References <201206150741.DAA24405@smc.vnet.net>

Show all headers | View raw


On 15 Jun 2012, at 09:41, GS wrote:

> I define the function f[x] as follows:
>
> f[x_] := 0 /; x < 0 || x > 1;
> f[x_] := 1
>
> It is zero outside of the interval [0,1]. This can be verified by plotting
> Plot[f[x], {x, -1, 2}]
>
> Now I integrate it from -1 to 2:
> In[270]:= NIntegrate[f[x], {x, -1, 2}]
> Out[270]= 3.
>
> The result should be 1, but it is 3. Clearly Mathematica ignores the fact that f[x] is zero outside of [0,1].
>
> This caused a lot of headache for me recently when I encountered such behavior in one of my research code.
> GS
>

To put it in a nutshell: this is not a bug but the wrong way to do what you are trying to do. Pattern based definitions are not suitable for use in mathematical computations. What happens in your case is that Mathematica tries to evaluate the function with symbolic argument and finds that the pattern condition does not hold, it then uses the second alternative and  integrates the function 1 getting the answer 3. You can avoid this by restricting your definition only to numerical input:


f[x_?NumberQ] := 0 /; x < 0 || x > 1;
f[x_?NumberQ] := 1

In[19]:= NIntegrate[f[x], {x, -1, 2}]

During evaluation of In[19]:= NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small. >>

During evaluation of In[19]:= NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in x near {x} = {1.00386}. NIntegrate obtained 0.999525 and 0.000761127 for the integral and error estimates. >>

0.999525

The answer is better but still this is hopelessly wrong approach. The right approach is to use a proper mathematica function intended for this purpose, such as Piecewise, UnitStep etc, e.g.

f[x_] := Piecewise[{{0, x < 0 || x > 1}}, 1]

 NIntegrate[f[x], {x, -1, 2}]

1.

Even better, you can do:

Integrate[f[x], {x, -1, 2}]

1


Andrzej Kozlowski=

Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread


Thread

Re: Bug in NIntegrate[]? Andrzej Kozlowski <akozlowski@gmail.com> - 2012-06-15 19:38 +0000

csiph-web