4
$\begingroup$

Consider this code:

fun = Compile[{{i, _Integer}},

  Catch[Do[
    If[j >= i, Throw[j]]

    , {j, 1, 10}]]

  ]

I put an integer as argument then if this argument is smaller than the iterator inside loop, it returns the number of that iterator. If input is smaller than the upper bound of loop everything is o.k but if it is bigger although the condition is not satisfied, it returns upper limit of the loop plus 1.

fun[15]
11 

Here is another example using Return:

fun = Compile[{{i, _Integer}},
  Do[

   If[j >= i, Goto["one"], Goto["two"]];
   Label["one"];
   Return[j];
   Label["two"];
   , {j, 1, 10}]]

I can't figure out what is wrong here. Is it possible that Compile doesn't recognize Null as the output so it tries to give a numerical output?!

This one works:

fun2 = Compile[{{myt, _Real}, {i, _Integer}},
  Module[{t = myt},
   Do[If[j >= i, Goto["one"], Goto["two"]];
    Label["one"];
    t = j;
    Break[];
    Label["two"];, {j, 1, 10}];
   t
   ]

  ]

If the condition isn't satisfied it returns the value you give to myt.

$\endgroup$

1 Answer 1

4
$\begingroup$

It looks like an error to me. If you study the compiled code, you see this:

Needs["CompiledFunctionTools`"]

CompilePrint[fun]

Mathematica graphics

The If test can be found in lines 4-5 resulting in a jump to 8 if the condition is not met, and another iteration in the loop. However, both when the condition is met and when the loop finishes, execution proceeds with line 9, resulting in a return value in both cases (which is not what the uncompiled function would do).

I believe the code would be correct if line 10 would be placed between lines 8 and 9. Line 7 seems to be superfluous.

$\endgroup$
2
  • $\begingroup$ How can I displace line 10? I thought in the Compile the code proceeds as when Compile isn't used. I cannot understand yet why without satisfying the condition there is a return value. $\endgroup$
    – MOON
    Feb 11, 2015 at 14:38
  • $\begingroup$ @yashar You can't displace line 10 (at least, I wouldn't know how). I was just indicating how the code would need to look like to mimic the uncompiled version's behaviour. I now believe the prime cause of the problem is that your code returns two possible return types, either an integer (when the argument is lower than the loop bound) or 'nothing'. This leads to a problem during compilation, where the compiler expects to return data of a single type. $\endgroup$ Feb 11, 2015 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.