# Discrete sampling of interpolating function returned by NDSolve

When solving an ODE with NDSolve, Mathematica returns an interpolation function. I need a discrete sampling of this function however. Naively, I can write this as (example):

slv = f[t]/. NDSolve[f'[t] == -f[t], f[t], {t,0,10}][[1]];
result = Table[{T, slv/.t->T}, {T,0,10,0.1}];


This is very slow for large times and fine sampling, and I have to do this for a large number of functions.

But in principle, Mathematica must already store a discretized representation of the function for the interpolation function. Is there a way to access this? Or do you have suggestions on how to make the code above faster?

Thanks!

-

A general remark to start with - speed is in the eye of the beholder.

Having said that, there are a couple of things not quite right with your code. First of all, NDSolve isn't doing what you think it does - it returns unevaluated because you didn't give an initial condition and you gave the wrong independent variable - you want to solve for f, not for f[t].

NDSolve[{f'[t] == -f[t], f[0] == 1}, f, {t, 0, 10}][[1]]


or something similar is probably closer to your needs.

Then, you can use something like

slv  = f /. NDSolve[{f'[t] == -f[t], f[0] == 1}, f, {t, 0, 10}][[1]];


and the table is created significantly faster (about a factor 275 on my machine)

result = Table[{T, slv[T]}, {T, 0, 10, 0.1}];


As InterpolatingFunction is listable, it is usually even faster to give it the range of numbers directly:

result = Transpose[{Range[0,10,0.1], slv[Range[0,10,0.1]}]


is faster again, though it only shows if you use a much smaller increment.

If your version of MMA knows about NDSolveValue, you can skip the step with the replacement (not that it saves any time, though):

slv = NDSolveValue[{f'[t] == -f[t], f[0] == 1}, f, {t, 0, 10}];

-
Nice answer. Clear & concise, +1. – ciao Mar 30 '14 at 22:25