uhoh
uhoh

Reputation: 3745

Displaying numpy matrices with fewer digits past the decimal

If I type M at my IDLE cursor to see the values in my matrix M, I get:

matrix([[  1.65930000e+03,  -2.34000000e+01,   1.50000000e+01,
       0.00000000e+00],
    [  3.30000000e+00,   1.68600000e+03,  -2.17000000e+01,
       0.00000000e+00],
    [ -1.70000000e+00,   5.00000000e+00,   1.69440000e+03,
       0.00000000e+00],
    [ -6.18000000e+01,   7.02000000e+01,  -4.18000000e+01,
       1.00000000e+00]])

Using the print statement form this answer only works if I convert the numpy matrix to an array first:

print(np.array_str(np.array(M), precision=2))

[[  1.66e+03  -2.34e+01   1.50e+01   0.00e+00]
 [  3.30e+00   1.69e+03  -2.17e+01   0.00e+00]
 [ -1.70e+00   5.00e+00   1.69e+03   0.00e+00]
 [ -6.18e+01   7.02e+01  -4.18e+01   1.00e+00]]

This is helpful, but it is a lot of typing to do when I want to debug. Is there a quicker way to reduce the precision when inspecting during debugging?

I tried this also, but it's much worse. I like that the scientific notation is removed, but the precision has expanded.

print(np.array_str(M.astype(np.ndarray), precision=2))

[ matrix([[1659.2999999999988, -23.399999999999995, 14.999999999999995, 0.0]], dtype=object)]
[ matrix([[3.3, 1686.0000000000002, -21.700000000000003, 0.0]], dtype=object)]
[ matrix([[-1.699999999999999, 5.000000000000001, 1694.4, 0.0]], dtype=object)]
[ matrix([[-61.799999999998704, 70.20000000000171, -41.799999999998306,
     1.0000000000000002]], dtype=object)]]

Upvotes: 1

Views: 652

Answers (1)

percusse
percusse

Reputation: 3106

NumPy comes with helper functions such as set_printoptions so you can use

 numpy.set_printoptions(precision=x)

to set the displayed precision.

Upvotes: 1

Related Questions