Search code examples
numpyformattingjuliarounding

How can I make Julia output vectors as pretty as Numpy?


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!


Solution

  • 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.