Re: Must tell Compile that Clip returns a number.
- To: mathgroup at smc.vnet.net
- Subject: [mg107748] Re: Must tell Compile that Clip returns a number.
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Thu, 25 Feb 2010 01:54:07 -0500 (EST)
- References: <hm3210$m7a$1@smc.vnet.net>
Hi, > (v7.0.1) I don't know whether this would be considered a bug or not, > but it took me a bit to figure out what was going on, so someone else > might find it useful. I think it is no bug, it just is one of the many inconveniences of the current Compile functionality.... > For some reason, Compile seems to expect Clip to return a list. (Maybe > because it takes a list argument.) For example: > > In[1]:= Compile[{x}, Clip[x, {0, 1}]][0] > CompiledFunction::cfte: > Compiled expression 0. should be a rank 1 tensor of > machine-size real numbers. > CompiledFunction::cfex: > Could not complete external evaluation at instruction 3; proceeding > with > uncompiled evaluation. > Out[1]= 0 > > A workaround is to use Compile's third argument to tell it that any > expression with head Clip will evaluate to a single number: > > In[2]:= Compile[{x}, Clip[x, {0, 1}], {{_Clip, _Real}}][0] > Out[2]= 0. While that saves you from the error message you will very likely be disappointed with the performance. If you look at the InputForm of the compiled function you will notice that the second argument is a nested list of numbers and one occurance of Clip. This means that the code needs to call back to the regular evaluation process to evaluate Clip which usually causes the compiled code to be hardly faster than the uncompiled code, in some cases it will even be slower. To really want to see speedup from Compile you need to take care that you only use constructs that can be compiled. Looking at the InputForm you will find that for the following only numbers appear in the nested list in the second argument which indicates that the whole body could be compiled for that case: Compile[{x}, Max[Min[x, 1], 0]] // InputForm Unfortunately all this seems to be documented only superficially and there is no known method but trial and error to determine which constructs can be compiled, but you should at least study this: tutorial/CompilingMathematicaExpressions hth, albert