I'm trying to speed up the recursive function that calculates Rotation numbers:
ClearAll[θ]
θ[n_, Ω_, k_] := θ[n, Ω, k] = θ[n - 1, Ω, k] + Ω -
k/(2 π) Sin[2 π θ[n - 1, Ω, k]]
θ[0, Ω_, k_] := 0
Notice that I'm using memoization. Here's the timing of the uncompiled function:
AbsoluteTiming[Table[θ[n, .2, 1]/n, {n, 1, 1000}];]
{0.016223, Null}
Now I tried compiling the recursive function:
ClearAll[compθ]
compθ =
Compile[{{n, _Integer}, {Ω, _Real}, {k, _Real}},
If[n == 0, 0,
compθ[n - 1, Ω, k] + Ω - k/(2 π)Sin[2 π compθ[n - 1, Ω, k]]],
{{compθ[_, _, _], _Real}},
CompilationOptions -> {"InlineCompiledFunctions" -> True,
"ExpressionOptimization" -> True}, RuntimeOptions -> {"Speed"}]
The timing of the compiled function is worse:
AbsoluteTiming[Table[compθ[n, .2, 1]/n, {n, 1, 1000}];]
{0.342844, Null}
Of course the timing could be improved if I could somehow use memoization with the compiled function, but I couldn't find any example that shows how to do it. Is it possible? I also noticed with CompilePrint
that the compiled function calls MainEvaluate, which is probably slowing the computation, but this comment suggests that this may be unavoidable. Is this true?