How to specify the format for printing an array of

2019-04-24 16:15发布

I have an array or matrix that I want to print, but only to three digits of precision. How do I do that. I tried the following.

> @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

Update: Ideally, I just want to call a function like printx("{.3f}", rand(m, n)) without having to further process my array or matrix.

标签: printf julia
4条回答
贪生不怕死
2楼-- · 2019-04-24 16:48

How about this?

julia> print(round(rand(3),3))
[0.188,0.202,0.237]
查看更多
在下西门庆
3楼-- · 2019-04-24 16:52

I would do it this way:

julia> map(x -> @sprintf("%.3f",x), rand(3))
3-element Array{String,1}:
 "0.471"
 "0.252"
 "0.090"
查看更多
放荡不羁爱自由
4楼-- · 2019-04-24 16:53

I don't think @printf accepts a list of arguments as you might be expecting.

One solution you could try it to use @sprintf to create formatted strings, but collect them up in a list comprehension. You might then use join to concatenate them together like so:

join([@sprintf "%3.2f" x for x in rand(3)], ", ")
查看更多
走好不送
5楼-- · 2019-04-24 17:10

The OP said:

Update: Ideally, I just want to call a function like printx("{.3f}", rand(m, n)) without having to further process my array or matrix.

This answer to a similar questions suggests something like 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]
查看更多
登录 后发表回答