2
$\begingroup$

Say I have 2 equations that take the same parameters and variables that I want to evaluate numerically in compiled code

cf1 = Compile[{{a, _Real}, {b, _Real}, {x, _Real, 1}}, N[a*x + b]];

which for example gives

cf1[2.3, 4.7, {1, 2, 3, 4}]

{7., 9.3, 11.6, 13.9}

and

cf2 = Compile[{{a, _Real}, {b, _Real}, {x, _Real, 1}}, N[a*x^2 - b]];

giving

cf2[2.3, 4.7, {1, 2, 3, 4}]

{-2.4, 4.5, 16., 32.1}

How do I make a function that I can just pass whichever equation I want and the parameters and it evaluates it numerically inside the Compile without going back to MainEvaluation

That is

cf[eq1, 2.3, 4.7, {1, 2, 3, 4}]

{7., 9.3, 11.6, 13.9}

and

cf[eq2, 2.3, 4.7, {1, 2, 3, 4}]

{-2.4, 4.5, 16., 32.1}
$\endgroup$
4
$\begingroup$
SetAttributes[compile, HoldFirst];
compile[code_] := With[{cc = code},
   Compile[{{a, _Real}, {b, _Real}, {x, _Real, 1}}, cc]
   ];

cf1 = compile[N[a*x + b]];
cf1[2.3, 4.7, {1, 2, 3, 4}]

cf2 = compile[N[a*x^2 - b]];
cf2[2.3, 4.7, {1, 2, 3, 4}]

{7., 9.3, 11.6, 13.9}

{-2.4, 4.5, 16., 32.1}

Edit

Maybe this is rather more what you are looking for? It undermines the very purpose of compilation, though.

SetAttributes[compile, HoldFirst];
compile[code_, aa_, bb_, xx_] :=  With[{cc = code}, Compile[{{a, _Real}, {b, _Real}, {x, _Real, 1}}, cc][aa, bb, xx]];
compile[N[a*x + b], 2.3, 4.7, {1, 2, 3, 4}]
$\endgroup$
  • $\begingroup$ I guess I didn't explain myself. I want to be able to call the same function twice, but with different equations as input. Here you still have to first separately compile for each equation. In my real code I have hundreds of equations that at various stages I want to evaluate with the same or slightly different parameters. $\endgroup$ – ThunderBiggi Oct 15 at 22:07
  • 1
    $\begingroup$ @ThunderBiggi as Henrik mentions -- that undermines the purpose of Compilation. What you want to do is create a compiled form of your equation for each equation of interest to make it efficient. $\endgroup$ – b3m2a1 Oct 15 at 22:32
  • $\begingroup$ This answers my question, so I accept it. But I see that I will have to reformualte my problem in order to take better advantage of Compile $\endgroup$ – ThunderBiggi Oct 15 at 23:41

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.