[Date Index]
[Thread Index]
[Author Index]
Re: Bug in NIntegrate[]?
*To*: mathgroup at smc.vnet.net
*Subject*: [mg126892] Re: Bug in NIntegrate[]?
*From*: Andrew Moylan <amoylan at wolfram.com>
*Date*: Fri, 15 Jun 2012 15:29:30 -0400 (EDT)
*Delivered-to*: l-mathgroup@mail-archive0.wolfram.com
This part of your definition,
f[x_] := 1
applies to *symbolic* values of x such as in f[x]. Therefore the evaluation precedes effectively along these lines:
NIntegrate[f[x], {x, -1, 2}]
=> NIntegrate[1, {x, -1, 2}]
=> 3.
To fix it:
One option is to restrict the class of cases where f[x] == 1 to only numbers:
Clear[f]
f[x_] := 0 /; x < 0 || x > 1
f[x_] := 1 /; Element[x, Reals]
This is not ideal (you will see NIntegrate works hard to locate the discontinuities at x==0 and x==1).
Better is to use Mathematica's piecewise functions: Piecewise, If, etc.
In[5]:= g[x_] := If[x < 0 || x > 1, 0, 1]
In[6]:= NIntegrate[g[x], {x, -1, 2}]
Out[6]= 1.
This is because NIntegrate recognizes such functions as likely sources of discontinuities and uses symbolic processing to split them up / simplify them first.
----- Original Message -----
> From: "GS" <vokaputs at gmail.com>
> To: mathgroup at smc.vnet.net
> Sent: Friday, June 15, 2012 12:41:03 AM
> Subject: Bug in NIntegrate[]?
>
> 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
>
>
Prev by Date:
**Re: Bug in NIntegrate[]?**
Next by Date:
**Re: Theta function integration bug**
Previous by thread:
**Re: Bug in NIntegrate[]?**
Next by thread:
**Re: fyi, small note on using Mathematica for object based programming**
| |