在Python 3.6中,以下工作用于为变量分配地球中原子的估计:
In[6]: atoms_in_earth = 10**50
In[7]: atoms_in_earth
Out[7]: 100000000000000000000000000000000000000000000000000
Run Code Online (Sandbox Code Playgroud)
但是,以下内容在Julia 1.0.0中不起作用:
julia> atoms_in_earth = 10^50
-5376172055173529600
julia> atoms_in_earth = BigInt(10^50)
-5376172055173529600
julia> atoms_in_earth = BigFloat(10^50)
-5.3761720551735296e+18
julia> atoms_in_earth = big(10^50)
-5376172055173529600
julia> atoms_in_earth = big"10^50"
ERROR: ArgumentError: invalid number format 10^50 for BigInt or BigFloat
Stacktrace:
[1] top-level scope at none:0
Run Code Online (Sandbox Code Playgroud)
我能够让这些方法起作用:
julia> atoms_in_earth = big"1_0000000000_0000000000_0000000000_0000000000_0000000000"
100000000000000000000000000000000000000000000000000
julia> float(ans)
1.0e+50
julia> atoms_in_earth = parse(BigInt, '1' * '0'^50)
100000000000000000000000000000000000000000000000000
julia> float(ans)
1.0e+50
Run Code Online (Sandbox Code Playgroud)
我希望在Julia有一个更简单的方法.
我错过了什么?
Julia 默认使用本机整数,这些可能会溢出.默认情况下,Python使用大整数(任意精度,它的大小限制取决于可用内存量)并且不会溢出(但由于此速度较慢).
您的第一个示例溢出Int64:
julia> atoms_in_earth = 10^50
-5376172055173529600
Run Code Online (Sandbox Code Playgroud)
在你将它们转换为bigs之前,你的第二,第三和第四个例子已经溢出了:
julia> atoms_in_earth = BigInt(10^50)
-5376172055173529600
julia> atoms_in_earth = BigFloat(10^50)
-5.3761720551735296e+18
julia> atoms_in_earth = big(10^50)
-5376172055173529600
Run Code Online (Sandbox Code Playgroud)
你的第五个例子不是一个有效的大文字:
julia> atoms_in_earth = big"10^50"
ERROR: ArgumentError: invalid number format 10^50 for BigInt or BigFloat
Run Code Online (Sandbox Code Playgroud)
但是你可以BigInt在你的例子中创建一个小数字10,任何进一步的操作将被提升为大算术,然后形成:
julia> x = 10
10
julia> typeof(x)
Int64
julia> x = BigInt(10)
10
julia> typeof(x)
BigInt
julia> big(10) == big"10" == big(10)
true
julia> y = x^50
100000000000000000000000000000000000000000000000000
julia> typeof(y)
BigInt
Run Code Online (Sandbox Code Playgroud)
在这种情况下,在计算之前50将其提升为a ,从而最终产生一个.BigIntx^50BigInt
julia> BigInt(10)^50 == big"10"^50 == big(10)^50
true
Run Code Online (Sandbox Code Playgroud)