# How to use result of NDSolve within a module?

I want to numerically solve a differential equation and use the resulting interpolating function for further calculations:

a = 5;
s = First@NDSolve[{f''[x] == a, f' == 0, f == 0}, f[x], {x, 0, 1}];
g[x_] = D[f[x] /. s, x];
g[0.5]


(Obviously this is not my actual code but a minimal example that shows my problem.) The code like this correctly displays the result 2.5.

However, if I put the same code inside a module:

test[var_] := Module[{a, s, g}, a = 5;
s = First@NDSolve[{f''[x] == a, f' == 0, f == 0}, f[x], {x, 0, 1}];
g[x_] = D[f[x] /. s, x];
g[0.5]]


The output is

test
f'[0.5]


What am I doing wrong? How do I use the result of NDSolve properly within a module?

(I suspect this question has been asked before, but I don't really know what to search for.)

Thanks to yarchik's answer I figured that simply replacing f for f[x] in the second argument of NDSolve fixes the issue. A shorter solution based on NDSolveValue would be

test[var_] := Module[{a, s, f}, a = 5;
f = NDSolveValue[{f''[x] == a, f' == 0, f == 0}, f, {x, 0, 1}];
f'[0.5]]


I am confident there will be some answers explaining what is wrong with your approach. In the meantime I would like to suggest a different way to deal with your problem. Namely, you are solving a second-order ODE and differentiating the result. One can reformulate this ODE as a system of 1st-order ODEs and get the derivative directly.

test[] := Module[{a, gg, f, g},
a = 5.;
gg = NDSolveValue[{g'[x] == a, f'[x] == g[x], g[0.] == 0., f[0.] == 0.},
g, {x, 0., 1.}];
gg[0.5]
]


Now check this out

 test[]
(* 2.5 *)

• Thanks! My ODE is in fact a bit more complicated than the simple example I gave here, and I need more complicated functions of the solution. So rewriting it into 1st order is not a feasible solution. However, simply using f instead of f[x] as the second argument in NDSolve seems to do the trick. Aug 20, 2021 at 8:17