# Length in Compile encounter “type Integer encountered in assignment of Type Real ”

Compile[{}, Module[{n}, n = Length[{1, 2, 3, 4}]; n = n/2]]


The above code will emit errors

Compile::cset: Variable n of type _Integer encountered in assignment of type _Real. >>

Compile::extscalar: n=n/2 cannot be compiled and will be evaluated externally. The result is assumed to be of type Real. >>

Compile::cset: Variable n of type _Integer encountered in assignment of type _Real. >>

Compile::extscalar: n=n/2 cannot be compiled and will be evaluated externally. The result is assumed to be of type Real. >>

Why? n = Length[{1, 2, 3, 4}] already make sure that n is integer, Why n=n/2 cannot be compiled?

• When it divides by 2, there's no guarantee that the result will be an integer (even though it is in this case). You can use n = Round[n/2] to keep the type as an integer – Jason B. Feb 5 '16 at 14:51
• @JasonB Thanks, Round works – matheorem Feb 5 '16 at 23:10

If you want integer division, use Quotient:

Compile[{}, Module[{n}, n = Length[{1, 2, 3, 4}]; n = Quotient[n, 2]]]


If you want n to be real instead of an integer, you can coerce it's type in a number of ways. For example, these will both result in n being real:

Compile[{}, Module[{n = 0.0}, n = Length[{1, 2, 3, 4}]; n = n/2]]

Compile[{}, Module[{n}, n = N[Length[{1, 2, 3, 4}]]; n = n/2]]


If you want to see how Compile has interpreted types, you can view the compiled routine like so:

<< CompiledFunctionTools;

cf = Compile[{}, Module[{n = 0.0}, n = Length[{1, 2, 3, 4}]; n = n/2]];

CompiledFunctionToString[cf]

(*
"
No argument
2 Integer registers
4 Real registers
1 Tensor register
Underflow checking off
Overflow checking off
Integer overflow checking on
RuntimeAttributes -> {}

T(I1)0 = {1, 2, 3, 4}
I1 = 2
R0 = 0.
Result = R1

1   R1 = R0
2   I0 = Length[ T(I1)0]
3   R2 = I0
4   R1 = R2
5   R2 = I1
6   R3 = Reciprocal[ R2]
7   R2 = R1 * R3
8   R1 = R2
9   Return
"
*)
`