在Julia中将浮点型二维数组转换为整型二维数组

10

我知道可以使用convert函数将Float64转换为Int64,但是当尝试将convert应用于2-D数组时,它无法正常工作。

julia> convert(Int64, 2.0)
2

julia> A = [1.0 2.0; 3.0 4.0]
2x2 Array{Float64,2}:
 1.0  2.0
 3.0  4.0

julia> convert(Int64, A)
ERROR: `convert` has no method matching convert(::Type{Int64}, ::Array{Float64,2
})
 in convert at base.jl:13

如何将二维浮点数数组转换为二维整数数组?

我的尝试

我可以使用以下代码完成这个任务,虽然它有点冗长,但是它可以工作。但我希望有更简单的方法来完成。

julia> A = [1.0 2.0; 3.0 4.0]
2x2 Array{Float64,2}:
 1.0  2.0
 3.0  4.0

julia> B = Array(Int64, 2, 2)
2x2 Array{Int64,2}:
 4596199964293150115  4592706631984861405
 4604419156384151675                    0

julia> for i = 1:2
           for j = 1:2
               B[i,j] = convert(Int64,A[i,j])
           end
       end

julia> B
2x2 Array{Int64,2}:
 1  2
 3  4

对我没有用的答案

               _
   _       _ _(_)_     |  A fresh approach to technical computing
  (_)     | (_) (_)    |  Documentation: http://docs.julialang.org
   _ _   _| |_  __ _   |  Type "help()" for help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 0.3.10 (2015-06-24 13:54 UTC)
 _/ |\__'_|_|_|\__'_|  |  Official http://julialang.org release
|__/                   |  x86_64-linux-gnu

julia> A = [1.2 3.4; 5.6 7.8]
2x2 Array{Float64,2}:
 1.2  3.4
 5.6  7.8

julia> round(Int64, A)
ERROR: `round` has no method matching round(::Type{Int64}, ::Array{Float64,2})
3个回答

19

你可以很容易地将一个2x2的浮点数数组转换为一个2x2的整数数组,只需决定如何处理舍入即可:

julia> A = [1.0 -0.3; 3.9 4.5]
2x2 Array{Float64,2}:
 1.0  -0.3
 3.9   4.5

julia> round.(Int, A)
2x2 Array{Int64,2}:
 1  0
 4  4

julia> floor.(Int, A)
2x2 Array{Int64,2}:
 1  -1
 3   4

julia> trunc.(Int, A)
2x2 Array{Int64,2}:
 1  0
 3  4

julia> ceil.(Int, A)
2x2 Array{Int64,2}:
 1  0
 4  5

你知道为什么我会得到输出 julia> round([1.2 3.4], Int64) ERROR: 'round' has no method matching round(::Array{Float64,2}, ::Type{Int64}) 吗? - I Like to Code
1
@ILiketoCode:你的做法是错误的。 - DSM
请看我编辑后的问题,我尝试了正确的方式,但仍然无法正常工作... - I Like to Code
1
这是0.4版本中的新功能。在0.3版本中,您可以执行convert(Array{Int}, round(A)) - mbauman
0.4 有稳定版本吗?最新版本似乎是 0.3.10。 - I Like to Code
显示剩余3条评论

4
你可以使用map函数,它可以保持矩阵的维度,不依赖于向量化方法:
julia> x = rand(2,2)
2x2 Array{Float64,2}:
 0.279777  0.610333
 0.277234  0.947914

julia> map(y->round(Int,y), x)
2x2 Array{Int64,2}:
 0  1
 0  1

我已经使用btime测试了DSM答案中的实现和广播方法,在运行时它们的性能相似 a = rand(10000,10000) (at)btime map(y->round(Int,y), a) # 501.133 ms vs (at)btime round.(Int, a) #489.392 ms - Hansang

-3

此答案适用于Julia v0.3。有关更新版本,请参见DSM的answer

使用int函数:

julia> a = rand(2,2)
2x2 Array{Float64,2}:
0.145651  0.362497
0.879268  0.753001

julia> int(a)
2x2 Array{Int64,2}:
0  0
1  1

我接受这个答案,因为它是最容易输入的。 - I Like to Code
4
在即将发布的0.4版本中,这已被弃用,而是采用@DSM答案中的方法,该方法明确说明了如何转换为“Int”。请注意,原文中的“how”指代的是具体的转换方式。 - mbauman
在 Julia 0.5 上:错误:UndefVarError:int 未定义。 - keiv.fly
这个答案显然已经不再适用了,因为它明显无法工作。 - Hansang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接