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

rak*_*h a 7 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
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*gge 7

这个怎么样?

julia> print(round.(rand(3); digits=3))
[0.188,0.202,0.237]
Run Code Online (Sandbox Code Playgroud)


Jul*_*ner 7

OP 说:

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

这个对类似问题的回答暗示了这样的事情:

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]
Run Code Online (Sandbox Code Playgroud)


Ran*_*tch 6

我会这样做:

julia> using Printf

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