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

标签 arrays floating-point integer julia

我知道可以将 Float64 转换为 Int64 使用convert函数。 不幸的是,当将 convert 应用于二维数组时,它不起作用。

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

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

我尝试过的

我可以使用以下代码来做到这一点, 这有点冗长,但它有效。 我希望有一种更简单的方法来做到这一点。

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})

最佳答案

在决定如何处理舍入后,您可以非常轻松地将 2x2 float 数组转换为 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

关于arrays - 在 Julia 中将浮点二维数组转换为整数二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31550045/

相关文章:

java - Java 填充二维数组中的特定行

python - 除以大整数时,Numpy 转换为 python float,这是一个错误吗?

c++ - 为什么这个 SOR 求解器的速度取决于输入?

c++ - 在没有初始化列表的情况下为c++中的头文件中的const int赋值

java - Java 中加密和解密文本文件的 key

javascript - 如何获取数组中的对象以显示在文档或控制台上

arrays - 类型 '___' 没有成员 'array'

delphi - 如何将 float 转换为具有 max 的字符串。 Delphi中的2位小数

c++ - 如何确定 float 何时通过整数边界

c++ - 将有符号整数转换为二进制 float 是否比逆运算便宜?