printf - 如何指定在 julia 中打印 float 数组的格式?

标签 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)) 这样的函数无需进一步处理我的数组或矩阵。

最佳答案

OP 说:

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对类似问题的回答表明了这样的事情:

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]

关于printf - 如何指定在 julia 中打印 float 数组的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38819425/

相关文章:

c - 为什么 printf 只打印字符串中的第一个单词?

.net - 为什么 printf 与托管字符串一起工作?

C: 当我将值放在括号中时,打印 %c 不起作用

c - snprintf() 溢出指定长度

julia - Julia 中的特征分解和 "composition"

dictionary - julia 0.6 中不同类型字典的向量

c++ - 打印指向成员字段的指针

julia - Julia 中的多参数递归类型和类型推断

julia - 为什么 Julia 中的 Base.match 函数返回 SubString{String} 类型而不是 String 类型?

Redis 请求在 1 到 3 毫秒内完成,耗时 300 毫秒