1
$\begingroup$

I'm trying to compile a rather long (takes quite some time to scroll through) expression that is in a variable but I'm unsure how it would be done in mathematica. I've tried the obvious

a=x^2;
Compile[{{x, _Real}}, a]
%[1]

or

x^2;
Compile[{{x, _Real}}, %]
%[1]

or

x^2;
Compile[{{xx, _Real}}, %/.{x->xx}]
%[1]

but they all give the same error:

CompiledFunction::cfse: Compiled expression x^2 should be a machine-size real number.

, however pasting the expression into the compile function does work:

Compile[{{x, _Real}}, x^2]
%[1]

While this is possible for simple expressions that are fixed, my expression is rather long and may change as I slowly find more and more errors in it, so I'd prefer if it could be compiled.

Even after searching the docs, seems like all the example has explicit expressions inside the compile function.

Does anyone know if it is possible to compile an expression stored in a variable?

$\endgroup$

1 Answer 1

4
$\begingroup$

Try

a = x^2;
cf = Compile[{{x, _Real}}, Evaluate@a]

cf[2]
(* 4 *)

Compile has the HoldAll attribute.

$\endgroup$
1
  • $\begingroup$ oh nice thanks! $\endgroup$
    – Ariana
    Dec 29, 2021 at 16:18

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.