Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #10472 > unrolled thread
| Started by | GS <vokaputs@gmail.com> |
|---|---|
| First post | 2012-06-15 07:42 +0000 |
| Last post | 2012-06-15 19:33 +0000 |
| Articles | 2 — 2 participants |
Back to article view | Back to comp.soft-sys.math.mathematica
Bug in NIntegrate[]? GS <vokaputs@gmail.com> - 2012-06-15 07:42 +0000
Re: Bug in NIntegrate[]? A Retey <albert.retey@gmail.com> - 2012-06-15 19:33 +0000
| From | GS <vokaputs@gmail.com> |
|---|---|
| Date | 2012-06-15 07:42 +0000 |
| Subject | Bug in NIntegrate[]? |
| Message-ID | <jrep0q$nrh$1@smc.vnet.net> |
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
[toc] | [next] | [standalone]
| From | A Retey <albert.retey@gmail.com> |
|---|---|
| Date | 2012-06-15 19:33 +0000 |
| Message-ID | <jrg2ls$sle$1@smc.vnet.net> |
| In reply to | #10472 |
Hi,
> 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
Another variant of the most frequently asked question :-). NIntegrate does evaluate the integrand symbolically, if not told otherwise. That symbolic evaluation will return 1 in your case:
In:=f[x]
Out:= 1
Since NIntegrate doesn't seem to accept the option Evaluated->False as some other functions which have the same problem do, you need to define the function so it only evaluates for numeric arguments:
ClearAll@f
f[x_?NumericQ] := 0 /; x < 0 || x > 1;
f[x_?NumericQ] := 1
That will make NIntegrate behave as expected (it will complain about bad convergence, but that I'd consider expected behaviour for that function :-). Note that it can do better if you use more "mathematical" ways to define your function, e.g. UnitStep, UnitBox or HeavsideTheta.
hth,
albert
[toc] | [prev] | [standalone]
Back to top | Article view | comp.soft-sys.math.mathematica
csiph-web