Re: Bug in NIntegrate[]?

• To: mathgroup at smc.vnet.net
• Subject: [mg126903] Re: Bug in NIntegrate[]?
• From: Andrzej Kozlowski <akozlowski at gmail.com>
• Date: Fri, 15 Jun 2012 15:33:19 -0400 (EDT)
• Delivered-to: l-mathgroup@mail-archive0.wolfram.com
• References: <201206150741.DAA24405@smc.vnet.net>

```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=

```

• Prev by Date: I: Bug in NIntegrate[]?
• Next by Date: Re: is Head[] part of the expression?
• Previous by thread: Re: Bug in NIntegrate[]?
• Next by thread: Re: Bug in NIntegrate[]?