1

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.

René
  • 4,594
  • 5
  • 23
  • 52

1 Answers1

3

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
Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62
  • How should the @saferintegers macro be used in the loop from my question? It does not seem to give me the Overflow Error from your example. – René May 05 '23 at 20:28
  • 1
    Suprisingly this macro seems not to handle loos. You can do instead: ` for i in SafeInt8[5, 10, 15, 20]` – Przemyslaw Szufel May 06 '23 at 11:30