@printf("%.3f", rand(3)-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:23:12 33 4
gpt4 key购买 nike

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

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com