a NIntegrate in the NIntegrate [closed]

Here is our problem:

Suppose g[y,z] and f[x,z] is complicated,we have to solve it numerically.

Writing this in Mathematica:

Clear["*"]
g[y_, w_] := 1/(w - y + I*0.1)
f[x_, w_] := (x*x)/(w - x + I*0.1)
NIntegrate[(g[k2, w]/(1 - NIntegrate[f[k1, w], {k1, 0, 30}])), {k2, 0,
30}, {w, -1, 2}]


the error message is

    NIntegrate::inumr: The integrand x^2/((2. +0.1 I)-x) has evaluated to non-numerical values
for all sampling points in the region with boundaries {{0,30}}.

• I vote to close this question as the one generated by simple syntactic errors. – Alexei Boulbitch Jan 11 '17 at 8:13
• Use g[y_, w_] :=, f[x_, w_] := – Feyre Jan 11 '17 at 10:37
• You can't numerically integrate NIntegrate[f[k1, w], {k1, 1, 30}], as w isn't numeric. – Feyre Jan 11 '17 at 10:39
• Use ? NumericQ: see mathematica.stackexchange.com/questions/18393/… – Michael E2 Jan 11 '17 at 12:13
• sorry,that I have missed _ in function definition g[y_,w_]. And adding ?_NumericQ didn't help. – ted.l Jan 11 '17 at 12:39

This might be a duplicate of one of the examples in User-defined functions, numerical approximation, and NumericQ, but there isn't one with nested NIntegrate.

ClearAll[f, g, h];
g[y_, w_] := 1/(w - y + I*0.1)             (* note use of patterns y_, w_ *)
f[x_?NumericQ, w_?NumericQ] := (x*x)/(w - x + I*0.1)
h[w_?NumericQ] := NIntegrate[f[k1, w], {k1, 0, 30}];
NIntegrate[(g[k2, w]/(1 - h[w])), {k2, 0, 30}, {w, -1, 2},
PrecisionGoal -> 2, AccuracyGoal -> 8]    (* for speed over accuracy; adjust as desired *)
(*  -0.0249226 - 0.0125844 I  *)


The trouble is that NIntegrate evaluates the integrand once symbolically. When the outer one evaluates the inner one, the symbol w does not have a value, so the inner NIntegrate complains. Note this error does not prevent the integral from being evaluated; but it is annoying and the messages slow things down.

For the use of patterns in defining functions, see the tutorial Defining Functions and its related tutorials.

Try this:

       g[y_, w_] := 1/(w - y + I*0.1)
f[x_, w_] := (x*x)/(w - x + I*0.1)
NIntegrate[(g[k2, w]/(1 - Integrate[f[k1, w], {k1, 0, 30}])), {k2, 0,
30}, {w, -1, 2}]

(*    -0.0249 - 0.0126 I   *)


Have fun!

• here,you have used "Integrate" to calculate the f[k1,w].But in fact I meet a more complicated f[k1,w],which can not be handled by "Integrate". – ted.l Jan 11 '17 at 9:09
• You cannot apply NIntegrate to an expression depending on a parameter. NIntegrate`requires that all parameters have numeric values. If this is not the case you will need to use tricks. But these may be only done individually, Then try to publish the real function you are interested in. – Alexei Boulbitch Jan 11 '17 at 18:06