Re: Compile problem: Mathematica 4
- To: mathgroup at smc.vnet.net
- Subject: [mg18806] Re: [mg18777] Compile problem: Mathematica 4
- From: David Withoff <withoff at wolfram.com>
- Date: Thu, 22 Jul 1999 08:19:25 -0400
- Sender: owner-wri-mathgroup at wolfram.com
> Hi. > > What is wrong with the following (simplified) compile statement? It seems > that the Compiler doesn't recognise that Round[] returns an object with a > Head of Integer. Can I explicitly tell the compiler that this is the case? > > Thanks for help/comments in advance. > > Paul > > Code follows: > > In[4]:= > f=Compile[{{x, _Real,1}}, i=Round[2.3]; x[[i]]++;Return[x]] > > Compile::cpintlt: > i at position 2 of x[[i]] should be either a non-zero integer or a > vector of \ > non-zero integers; evaluation will use the uncompiled function." > > Out[4]= > CompiledFunction[{x},i=Round[2.3]; x[[i]]++;Return[x], -CompiledCode-] > > In[5]:= > Round[2.3] //Head > > Out[5]= > Integer Try this instead: f=Compile[{{x, _Real,1}}, Block[{i,var=x}, i=Round[2.3]; var[[i]]++;Return[var]]] or f=Compile[{{x, _Real,1}}, Block[{var=x}, i=Round[2.3]; var[[i]]++;Return[var]], {{i, _Integer}}] In your example i is a global variable, and as such could be affected by global rules. There could, for example, be a global rule that causes i to redefine itself each time it is used. To be strictly logically correct the compiler needs to allow for this possibility. You can specify that i will always be an integer by including the type specification {i, _Integer} in the third argument of Compile. You don't need to do this in the current version of Mathematica (Version 4), which effectively ignores the possibility of such global effects, but the behavior of older versions of Mathematica (I am guessing that you are using an older version) is also correct. Alternatively, if you localize i, such as by using Block, that part of the problem will also go away. Localizing variables is a recommended approach to this sort of thing in any version of Mathematica. An unrelated problem with this example is that it tries to assign a value to a number. The expression x[[i]]++, where x is a list of numbers, picks out an element from that list and tries to increment it. Mathematica will not let you do that. That is the reason for introducing the variable var in the above examples. Dave Withoff Wolfram Research