# How to use NIntegrate inside FindRoot?

I am trying to use FindRoot on functions that involve NIntegrate, and Mathematica is throwing undesirable errors even when it gets an answer. I have tried the trick of using _?NumericQ for the function parameters, but the errors remain. What's the "correct" way to do this, so that Mathematica doesn't throw errors?

For example:

f[x_?NumericQ]=NIntegrate[Sin[x t^2]/Log[t],{t,2,3}]

Plotting f[x] for $$6 we see there is a root near 6.7:

So we solve for the root:

FindRoot[f[x],{x,6.7}]

Mathematica gives the correct answer after throwing three errors:

NIntegrate::inumr: The integrand Sin[a x^2]/Log[x] has evaluated to non-numerical values for all sampling points in the region with boundaries {{2,3}}.

NIntegrate::inumr: The integrand (x^2 Cos[a x^2])/Log[x] has evaluated to non-numerical values for all sampling points in the region with boundaries {{2,3}}.

NIntegrate::ncvb: NIntegrate failed to converge to prescribed accuracy after 9 recursive bisections in x near {x} = {4.00000008967591079907500673086366820702108881846470467280596494675}. NIntegrate obtained 3.1051550219984847*^-16 and 3.7022326395320475*^-13 for the integral and error estimates.

I'm mainly interested in getting rid of the first two, since the third seems to go away after fiddling with WorkingPrecision, PrecisionGoal, and AccuracyGoal. But as I'm fairly new to this, insight on all three would be appreciated.

• version 11.3 ,just FindRoot[NIntegrate[Sin[x t^2]/Log[t], {t, 2, 3}], {x, 6.7}] Feb 12, 2020 at 9:54

Just change the function definition to SetDelayed

f[x_?NumericQ] := NIntegrate[Sin[x t^2]/Log[t], {t, 2, 3}]
FindRoot[f[x], {x, 6.7}]
(*{x -> 6.74481}*)

• Ok, I see what's going on. I tried this and at first it didn't work. Then I cleared all variables/functions and it worked. I think I had previous versions stored of the same functions without SetDelayed that were being applied when the newer definitions with SetDelayed were failing. Feb 12, 2020 at 16:58

Try this

f = Interpolation[
Table[{x, NIntegrate[Sin[x t^2]/Log[t], {t, 2, 3}]}, {x, 6.6, 6.8, 0.05}]]


and then the following:

FindRoot[f[x] == 0, {x, 6.8}]

(*   {x -> 6.7448}    *)


Have fun!