如何指定在julia中打印Floats数组的格式?

时间:2016-08-07 23:13:43

标签: printf julia

我有一个我要打印的数组或矩阵,但只有三位精度。我怎么做。我尝试了以下内容。

> @printf("%.3f", rand())
0.742

> @printf("%.3f", rand(3))
LoadError: TypeError: non-boolean (Array{Bool,1}) used in boolean context 
while loading In[13], in expression starting on line 1

更新:理想情况下,我只想调用类似printx("{.3f}", rand(m, n))的函数,而无需进一步处理我的数组或矩阵。

4 个答案:

答案 0 :(得分:4)

我会这样做:

julia> map(x -> @sprintf("%.3f",x), rand(3))
3-element Array{String,1}:
 "0.471"
 "0.252"
 "0.090"

答案 1 :(得分:3)

这个怎么样?

julia> print(round(rand(3),3))
[0.188,0.202,0.237]

答案 2 :(得分:3)

我认为@printf不接受您可能期望的参数列表。

您可以尝试使用@sprintf创建格式化字符串,但在列表解析中收集它们的一种解决方案。然后,您可以使用join将它们连接在一起,如下所示:

join([@sprintf "%3.2f" x for x in rand(3)], ", ")

答案 3 :(得分:2)

OP说:

  

更新:理想情况下,我只想调用printx("{.3f}", rand(m, n))之类的函数,而不必进一步处理数组或矩阵。

This对类似问题的回答表明是这样的:

julia> VERSION
v"1.0.0"
julia> using Printf

julia> m = 3; n = 5;  
julia> A = rand(m, n)
3×5 Array{Float64,2}:
 0.596055  0.0574471  0.122782  0.829356  0.226897
 0.606948  0.0312382  0.244186  0.356534  0.786589
 0.147872  0.61846    0.494186  0.970206  0.701587

# For this session of the REPL, redefine show function. Next REPL will be back to normal.    
# Note %1.3f% spec for printf format string to get 3 digits to right of decimal.
julia> Base.show(io::IO, f::Float64) = @printf(io, "%1.3f", f)

# Now we have the 3 digits to the right spec working in the REPL.
julia> A
3×5 Array{Float64,2}:
 0.596  0.057  0.123  0.829  0.227
 0.607  0.031  0.244  0.357  0.787
 0.148  0.618  0.494  0.970  0.702

# The print function prints with 3 decimals as well, but note the semicolons for rows.
# This may not be what was wanted either, but could have a use.
julia> print(A)
[0.596 0.057 0.123 0.829 0.227; 0.607 0.031 0.244 0.357 0.787; 0.148 0.618 0.494 0.970 0.702]