2

I am dealing with a very simple code, which turns to be slow when I try to plot the final Piecewise function. Is the code computing back again the integral iteratively rather than just substituting d=2 and easily plotting?

AbsoluteTiming[g[t_, d_] = Integrate[d*Sin[t - t1]*f[t1], {t1, 0, t}, 
Assumptions -> t \[Element] Reals && d \[Element] Reals]] 
AbsoluteTiming[f[t1_] = Piecewise[{{-t1^2, 0 <= t1 <= 3}, {t1, t1 > 3}}]]
AbsoluteTiming[g[t, d]]
Plot[g[t, 2], {t, 0, 5}]

Even if I use /.d->2 inside Plot it is very slow.

So what I did is the following, trying to avoid the Evaluate and understand why I had problems (which seem to come from that 4th raw g[t,d]. Two ways worked well: 1) changing the order of the rows

AbsoluteTiming[
f[t1_] = Piecewise[{{-t1^2, 0 <= t1 <= 3}, {t1, t1 > 3}}]]
AbsoluteTiming[
g[t_, d_] = 
Integrate[d*Sin[t - t1]*f[t1], {t1, 0, t}, 
Assumptions -> t \[Element] Reals && d \[Element] Reals]]
AbsoluteTiming[g[t, d]]
Plot[g[t, 2], {t, 0, 5}]

or 2) changing the initial definition of g[t_,d_] into g[t_]deleting g[t,d] and defining a new function:

AbsoluteTiming[
g[t_] = Integrate[d*Sin[t - t1]*f[t1], {t1, 0, t}, 
Assumptions -> t \[Element] Reals && d \[Element] Reals]]
AbsoluteTiming[
f[t1_] = Piecewise[{{-t1^2, 0 <= t1 <= 3}, {t1, t1 > 3}}]]
h[t_, d_] = g[t]
Plot[h[t, 2], {t, 0, 5}]

I think Mathematica gets confused because of that g[t,d] definition after g[t_,d_]? Anyone can explain why?

Andrea G
  • 759
  • 3
  • 19

0 Answers0