What I would like to do in Mathematica is something like
f[x_] := a x
g[a_] := NIntegrate[f[x], {x, 0, 1}]
But then of course I get
g[1]
NIntegrate::inumr: The integrand a x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>
Out= NIntegrate[f[x], {x, 0, 1}]
But I found that I can circumvent the problem with
g[a_] := Hold[NIntegrate][f[x], {x, 0, 1}] // Evaluate // ReleaseHold // Evaluate
NIntegrate::inumr: The integrand a x has evaluated to non-numerical values for all sampling points in the region with boundaries {{0,1}}. >>
g[1]
Out= 0.5
I don't really understand why this works nor why the definition of g
throws an error. As I haven't found any other solution to my problem, I would really like to understand why my "solution" works which should also provide an answer to whether there is a simpler solution.
(I understand I can solve this simple problem with f[x_, a_]
but I have in fact a more complex environment in hand where this approach becomes inconvenient.)
f
which I then use in different combinations. So I would have to type expressions likeg[x,a,b,c]h[g[x,a,b,c],a,b,c]
instead of much clearerg[x]h[g[x]]
. This wouldn't matter if I was creating static code, but I am in fact prototyping and trying different combinations all the time. $\endgroup$ – azag0 Feb 21 '14 at 0:16g
asg[aa_] := Block[{a = aa}, NIntegrate[f[x], {x, 0, 1}]]
. $\endgroup$ – Alexey Popkov Feb 22 '14 at 8:13(f[x]^2 Sin[f[x]]+Cos[f[x]]/.a->1)+(f[x]^3 Cos[f[x]]+Sin[f[x]]/.a->2)
. Now I can of course do that easily withf[x,a]
, but it will be much more typing and during prototyping and with more parameters, it quickly becomes very time-consuming. $\endgroup$ – jhrmnn Feb 25 '14 at 12:35