I want to print the elements of an array of floating point numbers in the same format. In Python/Numpy, I do:
np.set_printoptions(formatter={‘float’: ‘{: 10.6f}’.format, ‘complexfloat’: ‘{: 10.6f}’.format})
and the simple command “print someArray” will print the elements of an array in a uniform format.
For example, I want arr = [1.0 2.583] to be printed as [1.000 2.583] rather than [1.0 2.583].
Is it possible to do this in Julia?
2 Likes
In theory you can do something like this:
julia> a = randn(4, 4)
4×4 Array{Float64,2}:
-1.93222 -0.427925 -0.502227 0.522741
0.240474 -1.13067 1.68355 0.839821
1.79882 0.918598 1.28506 -1.38715
0.0540847 0.197535 -0.204077 -0.282407
julia> Base.show(io::IO, f::Float64) = @printf io "%1.3f" f
julia> a
4×4 Array{Float64,2}:
-1.932 -0.428 -0.502 0.523
0.240 -1.131 1.684 0.840
1.799 0.919 1.285 -1.387
0.054 0.198 -0.204 -0.282
but I don’t know whether it’s recommended, or indeed how to undo it… ![:slight_smile: :slight_smile:](https://emoji.discourse-cdn.com/twitter/slight_smile.png?v=12)
5 Likes
This is what I was looking for.
Cool. Let us know of your experiences! (And choose your format string carefully, that one was just plucked from thin air.
)
It’s not recommended to do it this way. See https://github.com/JuliaLang/julia/issues/20509 for an issue whose fix can make this much nicer.
Perhaps the docs should contain some warnings about using this method on built-in types?