Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #10482
| From | Andrew Moylan <amoylan@wolfram.com> |
|---|---|
| Newsgroups | comp.soft-sys.math.mathematica |
| Subject | Re: Bug in NIntegrate[]? |
| Date | 2012-06-15 19:32 +0000 |
| Organization | Steven M. Christensen and Associates, Inc and MathTensor, Inc. |
| Message-ID | <jrg2ku$sl1$1@smc.vnet.net> (permalink) |
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@gmail.com>
> To: mathgroup@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
>
>
Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread
Re: Bug in NIntegrate[]? Andrew Moylan <amoylan@wolfram.com> - 2012-06-15 19:32 +0000
csiph-web