10
$\begingroup$

How to compile recursive formula when it relies on more than a few global variables (global to the topmost compiled function)? It is unreasonable to pass on all such variables to each recursive subroutine (there are more than one), as:

  • that would require a lot of tensor copying which would cause a slowdown;
  • even if passing globals would be possible, returning all affected globals from each subroutine would be tedious as each function must return a regular tensor of uniform data type.

Consider the following toy problem to calculate the factorial:

fact[x_] := Module[{sub, global = 1},
   sub[y_] := If[y > 0, global = global*y; sub[y - 1]];
   sub@x;
   global];

How to compile it without passing global to sub? While this code works nicely in the general Mathematica interface, the following compiled version will call MainEvaluate as there is a SetDelayed expression which the compiler cannot handle:

factC = Compile[{{x, _Integer}}, Module[{global = 1, sub},
    sub[y_] := If[y > 0, global = global*y; sub[y - 1]];
    sub@x;
    global]];

Is there any way to overcome this problem?

$\endgroup$
  • 1
    $\begingroup$ Related mathgroup post: Pass by reference for compiled functions No solution general enough though. $\endgroup$ – ssch Aug 26 '13 at 21:37
  • $\begingroup$ @ssch This pretty much tells me that what I want is impossible at the moment. I might be more successful writing code directly in C and than calling from under Mathematica... $\endgroup$ – István Zachar Aug 26 '13 at 21:52
  • $\begingroup$ Yea :( Perhaps passing the globals in the Compiled functions and then replace them with pointers in the CCodeStringGenerate can save some (writing) time. $\endgroup$ – ssch Aug 26 '13 at 22:00

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.