Re: Nested iterators in Compile

*To*: mathgroup at smc.vnet.net*Subject*: [mg55032] Re: [mg55010] Nested iterators in Compile*From*: "Christoph Lhotka" <lhotka at astro.univie.ac.at>*Date*: Thu, 10 Mar 2005 05:24:35 -0500 (EST)*Sender*: owner-wri-mathgroup at wolfram.com

Hello ! I would define your compiled function this way: In[..]:=g = Compile[{{n, _Integer}}, Module[{i, j, s = 0}, Do[s += j, {i, n}, {j, i}]; Print[s]], {{s, _Integer}, {i, _Integer}, {j, _Integer}}] (see Help Browser for more details on how to declare variables inside subexpressions at the end of Compile) The problem is, that you will get a similar error message, when you do not define initial values for i and j, but the function worked, as you can see here: In[..]:= g[100] Out[..]:=171700 To suppress the error message I defined a value for i and j, which should not be wrong, because, i and j are set inside the do - loop. But there seems to be a serious problem with it: In[..]:=In[..]:=g = Compile[{{n, _Integer}}, Module[{i=0, j=0, s = 0}, Do[s += j, {i, n}, {j, i}]; Print[s]], {{s, _Integer}, {i, _Integer}, {j, _Integer}}] any time, I use the function, it will nothing else return, but 0.. In[..]:=g[10/50/100/...] Out[..]:=0 for any other initial value for i I get different results, so... HOW CAN THE INITIAL VALUE FOR I INFLUENCE THE RESULT OF THE DO - LOOP? as you can see in an uncompiled version, this should not influence anything: In[..]:=G[n_] := Module[{i = 5, j = 3, s = 0}, Do[s += j, {i, n}, {j, i}]; Print[s]] In[..]:=G[100] Out[..]:=171700 Can anyone give some more explanation to this problem, some more information on how the function compile really works? On Wed, 9 Mar 2005 06:34:35 -0500 (EST) Maxim <ab_def at prontomail.com> wrote: > The fact that iterators work differently when used in Compile seems to > lead to a serious limitation: > > In[1]:= > Compile[{n}, > Module[{s = 0}, > Do[s += j, {i, n}, {j, i}]; > s > ]][10] > > CompiledFunction::cfse: Compiled expression i should be a machine-size > real number. > > CompiledFunction::cfex: External evaluation error at instruction 4; > proceeding with uncompiled evaluation. > > Out[1]= > 220 > > The iterator {j, i} is evaluated before any value is assigned to i, and > the evaluation of the compiled code fails (and if we add the > initialization i=0 before Do, we'll only get an empty loop as the result, > unlike the uncompiled version). So we have to resort to some workarounds > such as changing the inner iterator to {j, n} and adding If[j>i, > Continue[]] to the loop body, which of course decreases the performance. > > Maxim Rytin > m.r at inbox.ru > -- Christoph Lhotka -- University of Vienna Institute for Astronomy Tuerkenschanzstr. 17 1180 Vienna, Austria fon. +43.1.4277.518.41 mail. lhotka at astro.univie.ac.at