4

I need to integrate $f(t)$, a complicated function of time, over a very large period $T$. The code is simple:

g[T_]:=NIntegrate[f[t],{t,0,T}]

but what I also would like to do is to extract the result of NIntegrate at regular intervals, during same the evaluation, when $t=n\, k <T$, where $k$ is some number and $n=1,2..5$.

Is there a simple way to do this in Mathematica? or do I have to use Nintegrate over again for each value of $n$ ? Thanks.

user91411
  • 400
  • 3
  • 11

2 Answers2

6

You can try to use NDSolve instead. But without an example, hard to say, so I made up an example. Lets say your complicated function is

myComplicatedFunction[t_] := t

The following will do repeated NIntegration on the sampling points, just to show that we get same result with NDSolve

pts = Reap[
    NIntegrate[myComplicatedFunction[t], {t, -3, 5}, 
     EvaluationMonitor :> Sow[t]]][[2, 1]];

data = {#, NIntegrate[myComplicatedFunction[t], {t, -3, #}]} & /@ pts;

ListStepPlot[data, Mesh -> All,  AxesLabel -> {"t", "Area under the curve"}, 
     GridLines -> Automatic, GridLinesStyle -> LightGray, 
     PlotStyle -> Blue, MeshStyle -> Red]

Mathematica graphics

Now using NDSolve

sol = First@
   NDSolve[{f'[t] == myComplicatedFunction[t], f[-3] == 0}, f, {t, -3, 5}];
data = {#, Evaluate[f[#] /. sol]} & /@ pts;

Plotting the data above gives same plot as above, which is the value of the integral at each sample point. I think using NDSolve and evaluating the solution at the sampling point is more efficient than integrating repeatedly for different ranges.

Nasser
  • 143,286
  • 11
  • 154
  • 359
5

I would turn your problem into an ODE. For example, suppose f is:

f[t_] := Sin[LogGamma[t+1]]

Then, you could use NDSolveValue to get an interpolating function for g over the range of interest:

sol = NDSolveValue[{g'[t] == f[t], g[0] == 0}, g, {t, 0, 10}]

InterpolatingFunction[Domain: {{0.,10.}} Output: scalar]

The intermediate values are then obtained by evaluating sol at the desired points. For example, suppose you wanted the values of g for 1 .. 5:

sol[Range[5]]

{-0.0809247,0.213178,1.10363,1.68186,1.02489}

This is basically equivalent to evaluating NIntegrate for each intermediate value of interest:

NIntegrate[Sin[LogGamma[t+1]],{t,0,#}]&/@Range[5]

{-0.0809247,0.213178,1.10363,1.68186,1.02489}

Carl Woll
  • 130,679
  • 6
  • 243
  • 355