# Compiling function with predefined expression

I'm using the Compile function in Mathematica to compute say the following :

f=Compile[{x,_Real},Cos[x]]


Then I can compute f[x] for x taking any real value. Ok, let's say now that I have an expression like tmp=Cos[x].

My question is the following: Is there a way that I can compile the expression assigned to tmp without explicitly typing "Cos[x]" in the Compile function ? I.e. I want to do something like :

f=Compile[{x,_Real},tmp]


But that won't work it seems. In principle I'd like the value assigned to tmp to be a somewhat huge and complicated symbolic function of x that I would like to compile for numerical efficiency.

-
f = With[{tmp = Cos[x]}, Compile[{{x, _Real}}, tmp]] –  ciao Jun 22 '14 at 21:46
Great. I'll take that as an accepted answer If you post it as an answer. –  VanillaSpinIce Jun 22 '14 at 21:50

compiler[fun_] := Compile[{{x, _Real}}, fun]

compiler[Sin[x] + x^2 - 1/(1 + x)]


cf = compiler[Cos[x]];

cf /@ Range[-3., 3., 6/12.]

-

I think the only problem is the fact the the dummy variable x doesn't appear explicitly in tmp before it tmp is evaluated. To fix this, you could define tmp as a function instead. So, I think defining your function as follows should work:

tmp[x_] = Cos[x];
f = Compile[ {x_Real} , tmp[x] ];


Moreover, I don't think the definition of the tmp function has to be a delayed expression.

-
Kris, your reasoning is flawed. Please see CompilePrint[f] (after loading the package <<CompiledFunctionTools ) to understand that your approach doesn't work. The reason is the HoldAll attribute of Compile`. –  halirutan Jun 22 '14 at 22:27
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.8575876951217651, "perplexity": 1755.9714095016834}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2015-35/segments/1440644064951.43/warc/CC-MAIN-20150827025424-00336-ip-10-171-96-226.ec2.internal.warc.gz"}