4
votes

Coming from a Python / Matlab background, I'd like to understand better how Julia's Int64 overflow behaviour works.

From the documentation:

In Julia, exceeding the maximum representable value of a given type results in a wraparound behavior.

julia> x = typemax(Int64)
9223372036854775807

julia> x + 1
-9223372036854775808

Now, I did some experiments with numbers obviously larger than typemax(Int64), but the behaviour I see isn't consistent with the documentation. It seems like things don't always just wrap around. Is only a single wraparound allowed?

julia> x = (10^10)^(10^10)
0
julia> x = 10^10^10^10 
1   # ??

julia> x = 10^10^10^10^10  
10  # I'd expect it to be 1? 1^10 == 1?

julia> x = 10^10^10^10^10^10 
10000000000  # But here 10^10 == 10000000000, so now it works?


julia> typemax(Int64) > 10^19
true
julia > typemax(Int64) > -10^19
true

Can anyone shed light on the behaviour I am seeing?

EDIT:

Why does 9 overflow correctly, and 10 doesn't?

julia> 9^(10^14)
-1193713557845704703
julia> 9^(10^15)
4900281449122627585
julia> 10^(10^2)
0
julia> 10^(10^3)
0

Julia 0.5.0 (2016-09-19)

1

1 Answers

5
votes

What you are seeing the result of PEMDAS order of operations, specifically the parenthesis before exponentiation portion. This effectively becomes a right-to-left solving of these expressions.

julia> 10^(10^10) #happens to overflow to 0
0

julia> 10^(10^(10^10)) # same as 10 ^ 0
1

julia> 10^(10^(10^(10^(10^10)))) # same as x = 10^(10^(10^(10^(10000000000)))) -> 10^(10^(10^(0))) -> 10^(10^(1)) -> 10^ 10
10000000000

So it's really just a matter of working through the arithmetic. Or realizing you are going to have such large operations that you start using BigInt from the outset.