Home > Software engineering >  How can I make Julia output vectors as pretty as Numpy?
How can I make Julia output vectors as pretty as Numpy?

Time:02-02

If I do the following:

A = [
  2   1   3   0   0;
  1   1   2   0   0;
  0   6   0   2   1;
  6   0   0   1   1;
  0   0 -20   3   2
]
b = [10; 8; 0; 0; 0]
println(A\b)

The output is:

[8.000000000000002, 12.0, -6.000000000000001, -23.999999999999975, -24.000000000000043]

However, I would prefer it look similar to the way Numpy outputs the result of the same problem (EDIT: preferably keeping a trailing zero and the commas, though):

[  8.  12.  -6. -24. -24.]

Is there an easy way to do this? I could write my own function to do this, of course, but it would be pretty sweet if I could just set some formatting flag instead.

Thanks!

CodePudding user response:

The standard way to do it is to change the IOContext:

julia> println(IOContext(stdout, :compact=>true), A\b)
[8.0, 12.0, -6.0, -24.0, -24.0]

You can write your function e.g. (I am not trying to be fully general here, but rather show you the idea):

printlnc(x) = println(IOContext(stdout, :compact=>true), x)

and then just call prinlnc in your code.

CodePudding user response:

You could change the REPL behavior in Julia by overriding the Base.show method for floats. For an example:

Base.show(io::IO, f::Float64) = print(io, rstrip(string(round(f, digits=7)),'0') )

Now you have:

julia> println(A\b)
[8., 12., -6., -24., -24.]

As noted by @DNF Julia is using commas in vectors. If you want to have a horizontal vector (which is a 1xn matrix in fact) you would need to transpose:

julia> (A\b)'
1×5 adjoint(::Vector{Float64}) with eltype Float64:
 8.  12.  -6.  -24.  -24.

julia> println((A\b)')
[8. 12. -6. -24. -24.]
  • Related