2
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ If I define g[t_] rather than g[t_,d_] and then a new function, such as h[t_,d_]=g[t_] and then plot h[t,2], it works. Why? $\endgroup$ – Andrea G Mar 29 '17 at 9:10
  • $\begingroup$ Plot has the attribute HoldAll and as the documentation will tell you in the section Detail & Options sometimes an Evaluate will help, so this runs fast: Plot[ Evaluate@g[ t, 2 ], {t,0,5}]. $\endgroup$ – gwr Mar 29 '17 at 9:32
  • $\begingroup$ Have a look at 88571. $\endgroup$ – gwr Mar 29 '17 at 9:35
  • 1
    $\begingroup$ You could also evaluate at the beginning SetOptions[Plot, Evaluated -> True];. Or, the shortest way: Plot @@ {g[t, 2], {t, 0, 5}}, which is fast because of what @gwr told you. $\endgroup$ – Rolf Mertig Mar 29 '17 at 9:37
  • 1
    $\begingroup$ @gwr, correct, and yet another example of caveat emptor when using undocumented functionality. $\endgroup$ – J. M. will be back soon Mar 29 '17 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.