Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the format for printing an array of Floats in julia?

Tags:

printf

julia

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.

like image 455
rakesh a Avatar asked Aug 07 '16 23:08

rakesh a


4 Answers

How about this?

julia> print(round.(rand(3); digits=3))
[0.188,0.202,0.237]
like image 119
Michael Ohlrogge Avatar answered Sep 18 '22 18:09

Michael Ohlrogge


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]
like image 42
Julia Learner Avatar answered Sep 19 '22 18:09

Julia Learner


I would do it this way:

julia> using Printf

julia> map(x -> @sprintf("%.3f",x), rand(3))
3-element Array{String,1}:
 "0.471"
 "0.252"
 "0.090"
like image 28
Randy Zwitch Avatar answered Sep 20 '22 18:09

Randy Zwitch


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)], ", ")
like image 37
buruzaemon Avatar answered Sep 21 '22 18:09

buruzaemon