Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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).

share|improve this question
1  
Integrate[ f[x], {x, lb, ub}] /. (Integrate[x__] :> NIntegrate[x, Method -> "GaussKronrodRule"])? –  Öskå Jul 24 at 9:45

1 Answer 1

up vote 1 down vote accepted

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. >>

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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