# NIntegrate user defined function

I have the the function

f[a_] := Module[{solution, ans, x}, solution = NSolve[x + a == 4];


I want to integrate it by writing

NIntegrate[f[x],{x,1,5}


but I get this error message:

NIntegrate::inumr: The integrand x\$2682 has evaluated to non-numerical values
for all sampling points in the region with boundaries {{1,5}}.


In my problem the function is a bit more complicated but the principle is the same. Is there a nice way to integrate user defined equation-solving functions using for instance NIntegrate? I am aware that you can use f[x] to generate a table, interpolate the table, and finally integrate. However, is there perhaps a nicer way of doing this that avoids creating a interpolating function?

Your function f[a] doesn't return a value!

Try (thanks @SjoerdSmit for his helpful comment)

f[a_?NumericQ] := Block[{x}, x /. NSolve[x + a == 4, x][]];
NIntegrate[f[x], {x, 1, 5}]
(*4*)

• Thanks, it works! But I have a further question. If I write f[a_] := Module[{solution, ans,x}, solution = NSolve[x + a == 4]; ans = x /. solution; ans[]]. Then my function returns a value, but I still get the same error as before. What is the difference between what I do now, and what you do? Oct 7, 2019 at 9:05
• @MOOSE This answer is not correct. The integral should return 4; not 8. f[x] Inside NIntegrate evaluates prematurely to 2. (by solving x + x == 4) and is integrated afterwards. If you change x to b in NIntegrate you get a different answer because of this. The correct way to do this, is to use the pattern f[a_?NumericQ] := ... to prevent premature evaluation of f. Oct 7, 2019 at 15:53
• @MOOSE And upon further investigation, it's also recommended to localize x in f (like you did) because the evaluation can leak otherwise. Oct 7, 2019 at 16:03
• @SjoerdSmit Thanks for your hint, I modified my answer! Oct 8, 2019 at 6:18

your module definition is not correct, is this what you are looking for?

f[a_] := Module[{solution}, solution = NSolve[x + a - 4 == 0];
Return[solution]]
f

• Sorry, perhaps its the mondays. How is my module definition not correct? If I write f it returns 3. Oct 7, 2019 at 9:22
• There is one ] missing in the module and what is ans and x in your module definition? Oct 7, 2019 at 9:47