# How to use Compile

Consider the code below:

variable = Sin[x];
fun = Compile[{x}, variable ];
fun[1]


When I do this I get the error:

 CompiledFunction::cfse: Compiled expression Sin[x] should be a machine-size real number
CompiledFunction::cfex: Could not complete external evaluation at instruction 1; proceeding with uncompiled evaluation. >>


However, if I use:

 fun = Compile[{x}, Sin[x]];


Everything is fine. I need to compile as I presented first, the one which gives error because in my case variable is a huge very big expression. How can I achieve this goal?

-
Closely related: mathematica.stackexchange.com/questions/51294/… –  eldo Aug 14 at 15:37

You have a slight syntax error and a deeper problem binding the x in your "variable" to the x you have in the Compile function. Both can be fixed...

variable = Sin[x];
fun = Compile[{{x, _Real}}, Evaluate[variable]];
fun[1]


You must tell Compile that x is Real, hence the _Real (it only has zero dimensions so this is assumed).

The x in Compile[{{x etc) is local to Compile, its not the same x you have in Sin[x] so Evaluate forces variable to be evaluated before Compile looks at it.

-
I have 63 variables. How can I generate {x,_Real} automatically for them? Suppose they are Subscript[a,i,j]. –  yashar Aug 14 at 15:22
I'm not sure that Complile will work with subscripted symbols (almost certain it wont infact). I'd convert these to a3b4 or something before even trying. –  Ymareth Aug 14 at 15:32
I don't know about a3b4. What is a3b4? –  yashar Aug 14 at 15:40
I would setup a set of replacement rules Subscript[a,i,j]->aibj where aibj are actual symbols (a1b1, a1b2 etc). Use those rules on your expression variable and in the Compile function. –  Ymareth Aug 14 at 15:42

You could also use CompilationOptions

fun = Compile[{x}, variable, CompilationOptions -> {"InlineExternalDefinitions" -> True}];


This will automatically inline the definition of variable, which is unknown to the compiler otherwise.

-
Can I use some unknown parameters in the variable? –  yashar Aug 14 at 15:50
@yashar I don't completely understand what you mean with "unknown parameter". Is x in your example "unknown"? If you have multiple parameters, e.g. variable2 = Sin[x + a]; fun2 = Compile[{x, a}, variable2, CompilationOptions -> {"InlineExternalDefinitions" -> True}]; then fun2[1, 2] works, but fun2[1, b] will fall back to the uncompiled function. –  Karsten 7. Aug 14 at 16:15
I want to use this compiled function in NMinimize. Can NMinimize use a compiled function? –  yashar Aug 14 at 16:20
@yashar Yes, with "RuntimeOptions" -> {"EvaluateSymbolically" -> False}. See RuntimeOptions`. –  Karsten 7. Aug 14 at 16:45