Maximum value for Julia integer types

104 views Asked by At

Julia Integer types have a minimum and maximum value. When calculations go beyond those boundaries, results are 'incorrect'.

for i in Int8[5, 10, 15, 20]
    println(i, " -> ", i^2)
end

Result:

5 -> 25
10 -> 100
15 -> -31
20 -> -112

Is there an efficient way in Julia to raise an exception when this occurs?
This to prevent this from happening without noticing.

Maybe there are better solutions than raising an exception.

1

There are 1 answers

2
Przemyslaw Szufel On BEST ANSWER

Julia normally does not error on integer overflow as this results in faster code execution (and this is how arithmetic works on the CPU level)

You can however use @saferintegers macro to control the overflow.

julia> using SaferIntegers

julia> @saferintegers begin
       x = Int8(19)
       y = x * x
       end
ERROR: OverflowError: 19 * 19 overflowed for type Int8

In case of loops you need to use one of Safe* types:

julia> for i in SafeInt8[5, 10, 15, 20]
           println(i, " -> ", i*i)
       end
5 -> 25
10 -> 100
ERROR: OverflowError: 15 * 15 overflowed for type Int8

And the second option (perhaps less convenient):

julia> ⨰ = Base.Checked.checked_mul;

julia> Int8(9) ⨰ Int8(9)
81

julia> Int8(19) ⨰ Int8(19)
ERROR: OverflowError: 19 * 19 overflowed for type Int8