According to this Wolfram Blog post, one can speed up Mathematica code by substituting numerical values as soon as possible.
How does one substitute before the main expression is evaluated? The following timings show the problem:
In[881]:= Timing[
meanFirstPassage[N[.95* tenDesigner + (1. - .95) tenRandomUser], si,
gi]]
Out[881]= {0.46267, 4.3469}
In[880]:= Timing[
meanFirstPassage[
N[k* tenDesigner + (1. - k) tenRandomUser /. k -> .95], si, gi]]
Out[880]= {2.77539, 4.3469}
When I use the function above in Plot
it reverts to the slow version in which the inner expression involving k
is symbolically evaluated.
As noted by the response below, With
does the trick. My main goal was to speed up Plot
. Here is a self-contained example:
In[961]:= d = 100;
m1 = Table[RandomReal[], {d}, {d}];
m2 = N[Table[RandomInteger[], {d}, {d}]];
In[964]:= .95*m1 + (1. - .95)*m2; // AbsoluteTiming
Out[964]= {0.009045, Null}
In[965]:= k*m1 + (1. - k)*m2 /. k -> .95; // AbsoluteTiming
Out[965]= {0.059908, Null}
In[966]:= With[{k = .95}, k*m1 + (1. - k)*m2]; // AbsoluteTiming
Out[966]= {0.008615, Null}
In[967]:= Plot[Mean[k*m1 + (1. - k)*m2], {k, 0, 1}]; // AbsoluteTiming
Out[967]= {10.182414, Null}
In[968]:= Plot[With[{k = x}, Mean[k*m1 + (1. - k)*m2]], {x, 0., 1.}]; // AbsoluteTiming
Out[968]= {1.821481, Null}