1
$\begingroup$

I have read, that using Compile command can speed up evaluations in mathematica. I have a mathematical expression, which I evaluate using following command:

n = 5000
k = 10
c = n/k
a = Floor[n* Log[2]]
b = a + 1
pk1 = Table[
   Sum[Binomial[a, i]*StirlingS2[i, r]*(n - c)^(-i), {i, r, a}], {r, 
    1, c - 1}];

I was trying to use Compile to evaluate this, but I don't know how to 'tell' Compile that I want to evaluate for range {r,1,c-1}, I just made:

cf = Compile[{?}, 
  Sum[Binomial[a, i]*StirlingS2[i, r]*(n - c)^(-i), {i, r, a}]]

Can someone suggest how I should transmor my comment to compile commend? Or how I can speed up my evaluations in different way?

$\endgroup$
  • 2
    $\begingroup$ You need to look at this: mathematica.stackexchange.com/questions/1096/… - you'll see that Binomial and StirlingS2 cannot be compiled, so you are unlikely to benefit from compilation. $\endgroup$ – dr.blochwave Nov 4 '14 at 9:23
  • 2
    $\begingroup$ ParallelTable may speed up a bit. As well as putting n=5000. and not n=5000 $\endgroup$ – Rolf Mertig Nov 4 '14 at 22:33
3
$\begingroup$

As mentioned by blochwave, your code can't benefit from compilation. To speed up your code, take Rolf Mertig's advise may be the best. Making use of the Listable attribute of those arithmetical function will also help a little:

(* Tested under n = 1000, dual-core laptop *)
pk1 = Table[
    Sum[Binomial[a, i]*StirlingS2[i, r]*(n - c)^(-i), {i, r, a}], {r, 1, c - 1}]; //
AbsoluteTiming
{44.5980000, Null}
pk2 = ParallelTable[
    Sum[Binomial[a, i]*StirlingS2[i, r]*(n - c)^(-i), {i, r, a}], {r, 1, c - 1}]; //
AbsoluteTiming
{22.5580000, Null}
pk3 = ParallelTable[
    With[{i = Range[r, a]}, 
        Total[Binomial[a, i] StirlingS2[i, r] (n - c)^(-i)]], {r, c - 1}]; // 
AbsoluteTiming

pk1 == pk2 == pk3
{17.4624000, Null}
True
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.