1

I'm doing matrix factorization whose output matrix has non-integer entries. To make the display more compact, I would like to ask how to limit the number of decimals of results. Thank you so much!

import numpy as np
import scipy.linalg as la

A = np.array([[1, 0, 8, 7, 8, 1],
              [0, 1, 2, 8, 9, 2],
              [5, 1, 0, 6, 10, 3],
              [5, 4, 4, 8, 10, 4]])

(P, L, U) = la.lu(A)

F = np.array(sorted(U, key=lambda x: tuple(x!=0), reverse=False))
print(F)

[[ 0.          0.          0.          6.85483871  8.51612903  1.62903226]
 [ 0.          0.          8.26666667  5.93333333  6.          0.46666667]
 [ 0.          3.          4.          2.          0.          1.        ]
 [ 5.          1.          0.          6.         10.          3.        ]]

PS: I would like to ask for a global setting instead of repeating apply the function round to each output.

Akira
  • 2,594
  • 3
  • 20
  • 45
  • 1
    Here is a similar answer to your question: https://stackoverflow.com/questions/455612/limiting-floats-to-two-decimal-points – Panda50 Jun 01 '20 at 22:07
  • @Panda50 I would like to ask for a global setting instead of repeating apply the function `round`. – Akira Jun 01 '20 at 22:08
  • 1
    With np.array it's really easy! Look at this answer too: https://stackoverflow.com/a/37822702/13350827 – Panda50 Jun 01 '20 at 22:13
  • @Panda50 With your solution, I must apply function `np.around` to each result I want to print. – Akira Jun 01 '20 at 22:14
  • 1
    Not really, try this on your code: print(np.around(F,2)) I think it'll give you what you want to obtain! – Panda50 Jun 01 '20 at 22:17
  • @Panda50 I mean: if I have 3 matrices `A,B,C` then I have to `print(np.around(A,2))` and `print(np.around(B,2))` and `print(np.around(C,2))`. – Akira Jun 01 '20 at 22:20
  • Yes, from my point of view it's ok because it answer your question. Let's wait for another answer! – Panda50 Jun 01 '20 at 22:23
  • I really appreciate your help @Panda50. – Akira Jun 01 '20 at 22:25

1 Answers1

2

You can use numpy.around:

import numpy as np
import scipy.linalg as la

A = np.array([[1, 0, 8, 7, 8, 1],
              [0, 1, 2, 8, 9, 2],
              [5, 1, 0, 6, 10, 3],
              [5, 4, 4, 8, 10, 4]])

(P, L, U) = la.lu(A)

F = np.array(sorted(U, key=lambda x: tuple(x!=0), reverse=False))
F = list(map(lambda x: np.around(x,2),F)) # 2 here is the number of decimals
print(F)