Simpler Syntax For Conversion to integers

I am trying to find some simpler syntax for variable type converters. In my scripts, I have been declaring variables for controlling the behavior like this:

FFT_Size = 128

I may then use this variable to control loops, create arrays, etc. The problem is that the numbers are treated as floats and I need them to be integers. For example in C, if I assign a float to an int, it will auto truncate the value. In many cases I need to divide this control variable by an integer.

For example:


Data = Array{Complex64}(convert(UInt32,floor(FFT_Size/2)))

I would like to simple do something like this:


Data = Array{Complex64}(FFT_Size/2)

In this case I am simple trying initialize an array of complex numbers with a length of the FFT_Size. I am sure there is a much simpler way of achieving this.

It does not seem like globals can have a type assigned like this:


FFT_Size::UInt32

Lastly it seems if I doing something like this:


a = 128::Int

the expression


a/2 or a/2::Int

will always yield a Float64

I often have to create new arrays where the length is dependent on some prior computation. Maybe I am simply approaching this incorrectly?

Use div, which performs integer division. If you’re in the REPL or an editor with tab-completion, you can also use ÷ (typed as \div <tab>).

julia> 11 ÷ 4
2

julia> typeof(ans)
Int64
3 Likes

128 is an integer, and is treated as such. If you want a floating point number, you have to write 128.0. That’s not your problem. What is hitting you is that / does ‘floating point division’. It has to, otherwise 1/2 wouldn’t give you 0.5.

As @stillyslalom says, in order to keep the output as integers you have to explicitly ask for it, by using integer division, div.

2 Likes

The div function also produces an integer by rounding down. If FFT_Size happens to be odd I would venture that your Data array will be too short by 1.

Note that you can use a::Int = 128 to ensure that a stays as an integer. In this case if you do floating point division you might run into some InexactErrors. For example

julia> function div2(a)
       b::Int = a
       b = b/2
       return b
       end
div2 (generic function with 1 method)

julia> div2(128)
64

julia> div2(129)
ERROR: InexactError: Int64(Int64, 64.5)
Stacktrace:
 [1] Type at ./float.jl:692 [inlined]
 [2] convert at ./number.jl:7 [inlined]
 [3] div2(::Int64) at ./REPL[10]:3
 [4] top-level scope at none:0
2 Likes
floor(Int, 9/2)
1 Like