0
$\begingroup$

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?

$\endgroup$
1
$\begingroup$

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][[1]]];
NIntegrate[f[x], {x, 1, 5}]
(*4*)
$\endgroup$
4
  • $\begingroup$ 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[[1]]]. 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? $\endgroup$
    – MOOSE
    Oct 7 '19 at 9:05
  • $\begingroup$ @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. $\endgroup$ Oct 7 '19 at 15:53
  • $\begingroup$ @MOOSE And upon further investigation, it's also recommended to localize x in f (like you did) because the evaluation can leak otherwise. $\endgroup$ Oct 7 '19 at 16:03
  • $\begingroup$ @SjoerdSmit Thanks for your hint, I modified my answer! $\endgroup$ Oct 8 '19 at 6:18
0
$\begingroup$

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[5]
$\endgroup$
2
  • $\begingroup$ Sorry, perhaps its the mondays. How is my module definition not correct? If I write f[1] it returns 3. $\endgroup$
    – MOOSE
    Oct 7 '19 at 9:22
  • $\begingroup$ There is one ] missing in the module and what is ans and x in your module definition? $\endgroup$
    – acoustics
    Oct 7 '19 at 9:47

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.