来自Python/Matlab背景,我想更好地理解Julia的Int64溢出行为是如何工作的.
从文档:
在Julia中,超出给定类型的最大可表示值会导致环绕行为.
julia> x = typemax(Int64)
9223372036854775807
julia> x + 1
-9223372036854775808
Run Code Online (Sandbox Code Playgroud)
现在,我做了一些实验,数字明显大于typemax(Int64),但我看到的行为与文档不一致.似乎事情并不总是只是环绕.只允许一个环绕?
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
Run Code Online (Sandbox Code Playgroud)
任何人都可以了解我所看到的行为吗?
编辑:
为什么9正确溢出,10不正确?
julia> 9^(10^14)
-1193713557845704703
julia> 9^(10^15)
4900281449122627585
julia> 10^(10^2)
0
julia> 10^(10^3)
0
Run Code Online (Sandbox Code Playgroud)
朱莉娅0.5.0(2016-09-19)
你看到PEMDAS操作顺序的结果,特别是取幂部分之前的括号.这有效地成为这些表达式的从右到左的解决方案.
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
Run Code Online (Sandbox Code Playgroud)
所以这只是一个完成算术的问题.或者意识到你将拥有如此庞大的操作,从一开始就开始使用BigInt.