0
$\begingroup$

I have an analytic expression which involves several integrals

Integrate[f[x], {x, lb, ub}]

where the functions f and bounds lb, ub differ.

I now would like to

  1. replace Integrate by NIntegrate, while leaving the arguments of Integrate unchanged
  2. specify a specific method for numerical integration, such as Method -> "GaussKronrodRule"

I manage to accomplish (1) by

Integrate[f[x], {x, lb, ub}] /. Integrate -> NIntegrate

but I have no clue how to do (2).

$\endgroup$
1
  • 1
    $\begingroup$ Integrate[ f[x], {x, lb, ub}] /. (Integrate[x__] :> NIntegrate[x, Method -> "GaussKronrodRule"])? $\endgroup$
    – Öskå
    Jul 24 '14 at 9:45
1
$\begingroup$

You could use the replacement rule that Öskå already provided:

Integrate[f[x], {x, lb, ub}] /. 
 Integrate[x__] :> NIntegrate[x, Method -> "GaussKronrodRule"]

However this will throw one unnecessary error message:

Integrate::argmu: Integrate called with 1 argument; 2 or more arguments are expected. >>

You could wrap the left-hand-side of the rule in HoldPattern, but instead I suggest:

nInt = NIntegrate[##, Method -> "GaussKronrodRule"] &;

Integrate[f[x], {x, lb, ub}] /. Integrate -> nInt

One more detail that may be important is handing Options within the original Integrate.
Since the Options for Integrate will not be accepted by NIntegrate you should make sure that they are stripped. Here is a function that does this and perform the transformation:

intToNInt = # /. 
    HoldPattern[Integrate[x__, OptionsPattern[]]] :> 
     NIntegrate[x, Method -> "GaussKronrodRule"] &;

(This uses HoldPattern as I mentioned earlier.)

Now:

Integrate[f[x], {x, lb, ub}, GenerateConditions -> True, 
  PrincipalValue -> True] // intToNInt
NIntegrate[f[x], {x, lb, ub}, Method -> "GaussKronrodRule"]

This still gives one error message but that is simply the result of your transformation on the given example:

NIntegrate::nlim: x = lb is not a valid limit of integration. >>

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.